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 trialFlore W
4,744 PointsWhy 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
Treehouse Moderator 68,441 PointsYou 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.
Tyler Wells
Python Development Techdegree Student 2,678 PointsTyler Wells
Python Development Techdegree Student 2,678 PointsHi 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
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsHi 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
:Hope this helps. Post back if you need more help. Good luck!!!
Tyler Wells
Python Development Techdegree Student 2,678 PointsTyler Wells
Python Development Techdegree Student 2,678 PointsAhhh cool. So an iterator is different than an iterable. Got it. Thanks!!
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsExactly. Here is a StackOverflow post that covers more about the difference between interators and iterables.