StopIteration in the if clause of a generator expression

stephen.thorne at gmail.com stephen.thorne at gmail.com
Sun Apr 3 18:22:07 EDT 2005


This is all just making everything far too complicated. What you really
want to do is quite simple:

import itertools
def condition(x): return x < 5

list(itertools.takewhile(condition, (i for i in range(10))))

The 'Stop Iteration In Generator Expression' problem was solved in the
language that List Comprehensions came from, Haskell. Haskell's basic
library, prelude, had a series of functions that have found their way
into the itertools toolbox. I highly recommend having a read of the
itertools docs if you want to continue hacking around with generators.

Regards,
Stephen Thorne




More information about the Python-list mailing list