Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Flore W4,731 Points
Why do we need rows = list(artreader)?
The code in the video is:
import csv with open('museum.csv',' newline ='') as csvfile: artreader = csv.DictReader(csvfile, delimiter='|') rows = list(artreader) for row in rows: print(row['artifactNumber'])
and I get all the artifact numbers.
If I delete the line 'rows = list(artreader)' and replace 'for row in rows' by 'for row in artreader', I get exactly the same result. So why do I need it?
Chris FreemanTreehouse Moderator 68,063 Points
You are correct, in that, you code is equivalent. The object
artreader is an iterator so it can be used directly as the target of a
for loop. One drawback on iterators is they can only be used once. Expanding the iterator into a the list
rows might be useful if the code intends to use the data multiple times.