grokking generators and iterators

Bob Horvath usenet at horvath.com
Sun May 12 01:03:54 EDT 2002


Alex Martelli wrote:
> 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.
>

Well, didn't know which one of these many helpful posts to reply to. 
Thanks to all, very enlightening.

Your responses have already given me ideas on how to finish off the rest 
of the problem.  I left out some of the nasty details as to why it is 5 
line chunks. Mainly because it was delimited with optional pieces until 
a new mandatory element came along, and a new line was created.  The 
"less than 5" soltions helped quite a bit in dealing with the "how many 
delimiters are there" problem to which I hadn't even asked for a solution.


While I have been teaching myself python for many interations (self 
classes, both old and new, with the length of time not mattering how 
long), I feel like I am part of a new generation of pythonistas, no 
matter how you divide it.

Bob





More information about the Python-list mailing list