Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python CSV

Flore W
Flore W
4,744 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?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 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.

Hi Chris, I know you answered this a while ago...just coming across it here. But what do you mean that you can only use an iterator once? Thanks!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Hi Tyler, good question.

In the code above, artreader is an iterator. As an iterator, it offers up each item following the __next__ protocol. After the last item is offered up and there are no more items, then the iterator will raise a StopIteration error. Calling an iterator again will not restart at the beginning, rather it will only yield another StopIteration error. for loops stop when a StopIteration error is raised.

With this understanding, there are two ways to use artreader:

# style one: save iterator contents in list
rows = list(artreader)
for row in rows:
    # do something with each row 
for row in rows:
    # do something else with each row 
    # this second loop works completely 

# style two: use iterator directly
for row in artreader:
    # do something with each row
for row in artreader:
    # this code block will not execute since
    # the iterator has already been exhausted 

Hope this helps. Post back if you need more help. Good luck!!!

Ahhh cool. So an iterator is different than an iterable. Got it. Thanks!!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Exactly. Here is a StackOverflow post that covers more about the difference between interators and iterables.