grokking generators and iterators

Bob Horvath usenet at horvath.com
Sat May 11 02:14:07 EDT 2002


David Eppstein wrote:
> In article <3CDCAEDC.2030103 at horvath.com>,
>  Bob Horvath <usenet at horvath.com> wrote:
> 
> 
>>I don't think it matters what the format is. It is a repeating pattern 
>>of 5 lines.
>>
>>How would you suggest writing a generator that spits out 5 line chunks 
>>of a file at a time?
> 
> 
> 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.




More information about the Python-list mailing list