[Tutor] Loop not iterating

Alan Gauld alan.gauld at btinternet.com
Mon Jun 29 01:56:17 CEST 2015


On 28/06/15 20:32, Nym City via Tutor wrote:
> import csv
> domains = open('top500domains.csv')
> domainsReader = csv.reader(domains)
> domainLists = list(domainsReader)
> for domain in domainLists:
>       something = ("www." + str(domain))

You overwrite something each time round the loop.

> print(something)

And because this is outside the loop it will only ever print the last 
item. But since you have only stored one item thats OK...

> 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"

Ypu are saving each item into something but then next time round you 
throw away the old one and replace it wotyh the next.

You should create a list and store it there. But you already
have that list, its called domainLists. I'm not sure what you
think you are achieving here?

>  - and later print "something" it contains only 1 entry from my csv file.

Because the print is outside the loop and only prints the value
of something after the loop completes. That will be the last entry.

> On the other hand, instead of saving of loop output to the variable
 > "something" - if I just print, I get all 500 entries displayed.

Because you are printing inside the loop. So it prints each item.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list