grokking generators and iterators

Alex Martelli aleax at aleax.it
Sat May 11 02:23:30 EDT 2002


Bob Horvath wrote:
        ...
>> def fiveatatime(L):
>>     L = iter(L)
>>     while 1:
>>         yield (L.next(),L.next(),L.next(),L.next(),L.next())
>> 
>> then call fiveatatime(file)
>> 
>> This will group each five line chunk into a tuple of five strings.
>> It will throw away lines at the end that are not a multiple of five --
>> you need to specify more carefully what to do if that is a problem.
> 
> That will indeed work, I think, but I am not sure I understand the end
> condition.  What happens when you "next()" off of the end? I was
> expectin an exception, but it seems to get swallowed.

You do get an exception, StopIteration, and the for statement uses
that as the indication that iteration is finished.  This is how any
iterator indicates the end of the iteration, part and parcel of the
iterator protocol.


Alex




More information about the Python-list mailing list