[Tutor] Loop not iterating

Steven D'Aprano steve at pearwood.info
Mon Jun 29 04:52:07 CEST 2015


Hi Nym, and welcome,

On Sun, Jun 28, 2015 at 07:32:40PM +0000, Nym City via Tutor wrote:

[...]
> for domain in domainLists:
>      something = ("www." + str(domain))
> print(something)
> 
> My program reads in a CSV file that has 500 list of domains. However, 
> when I save the output of my loop to the variable name "something" - 
> and later print "something" it contains only 1 entry from my csv file.

Of course it does. Each time you go through the loop, you change the 
value of "something" to the new value.

If you do this:

x = 23
x = 42
print(x)


What do you expect to print? Hopefully 42.

If you want multiple values, you need something like a list:

x = []
x.append(23)
x.append(42)
print(x)


Of course, in *this* case, there is an easier way to create a list with 
two values:

x = [23, 42]

but in the general case where you don't know how many values you will 
have, you need to add them using append inside a loop.


-- 
Steve


More information about the Tutor mailing list