How to stop iteration with __iter__() ?
Terry Reedy
tjreedy at udel.edu
Tue Aug 19 15:06:24 EDT 2008
ssecorp wrote:
> I want a parse a file of the format:
> movieId
> customerid, grade, date
> customerid, grade, date
> customerid, grade, date
> etc.
>
> so I could do with open file as reviews and then for line in reviews.
>
> but first I want to take out the movie id so I use an iterator.
>
> then i want to iterate through all the rows, but how can I do:
> while movie_iter != None:
>
> because that doesn't work, itraises an exception, StopItreation, which
> according to the documentation it should. But catching an exception
> can't be the standard way to stop iterating right?
Catching StopIteration *is* the usual way to stop iterating with an
iterator. Using while, one must be explicit:
it = iter(iterable)
try:
while True:
item = next(iter) # 2.6,3.0
f(item)
except StopIteration:
pass
but the main reason to write the above is to show the advantage of
simply writing the equivalent (and implicit)
for item in iterable:
f(item)
;-)
In your case, the standard Python idiom, as Jon said, is
it = iter(iterable)
next(it) # 2.6, 3.0
for for item in iterable:
f(item)
The alternative is a flag variable and test
first = True
for for item in iterable:
if first:
first = False
else:
f(item)
This takes two more lines and does an unnecessary test for every line
after the first. But this approach might be useful if, for instance,
you needed to skip every other line (put 'first = True' after f(item)).
Terry Jan Reedy
More information about the Python-list
mailing list