[Tutor] Loop not iterating

Steven D'Aprano steve at pearwood.info
Tue Jun 30 04:19:01 CEST 2015


On Tue, Jun 30, 2015 at 01:05:13AM +0000, Nym City wrote:
> Hello all,
> Thank you for your time and tips. The reason why I decided to create a 
> loop is because the output is cleaner and did not require any 
> formatting. However, based on what I have learned from all of your 
> responses, that is not going to work with what I am trying to do.

There's no reason why a loop wouldn't work, although there may be better 
solutions, and a loop is a much better solution to what you have below.


> Here is the updated code:
> import csvdomains = open('top500domains.csv')domainsReader = 
> csv.reader(domains)domainLists = 
> list(domainsReader)print('\n'.join(["https://www ." + str(lst) for lst 
> in domainLists]), sep='\n')

Please ensure you post as *plain text*, not HTML (so called "rich text" 
or "formatted text"). When you post as HTML, many mail programs mangle 
the code and destroy the formatting, as you can see above.

Reconstructing what the code should look like on five separate lines:

import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
domainLists = list(domainsReader)
print('\n'.join(["https://www ." + str(lst) for lst in domainLists]), sep='\n')


The first three lines seem to be correct, but the next:

    domainLists = list(domainsReader)

is unnecessary and should be deleted. However, the last line does too 
much, and the wrong thing too. A simple loop is *much* better here, 
since you just print the domains and don't need to keep them for further 
processing:

for row in domainLists:
    # row is a list of *one or more* fields; in this case, there
    # is only one field per row, the domain name
    domain = "https://www." + row[0]
    print(domain)

Suppose that you do need to keep the domains for later, as well as print 
them. Then you can do this instead:


import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
# Make a list of the domains.
domains = ["https://www." + row[0] for row in domainsReader]
# Print each domain.
for domain in domains:
    print(domain)
# Now continue to do more work on the list of domains...



-- 
Steve


More information about the Tutor mailing list