grokking generators and iterators

David Eppstein eppstein at ics.uci.edu
Sat May 11 01:41:54 EDT 2002


In article <3CDCB6AF.8030903 at horvath.com>,
 Bob Horvath <usenet at horvath.com> 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 would typically use this in a for-loop:

for chunk in fiveatatime(file):
    do something

The exception terminates the loop.

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list