[ x for x in xrange(10) when p(x) ]

bonono at gmail.com bonono at gmail.com
Thu Nov 10 21:20:01 EST 2005


Bengt Richter wrote:
> If you want to terminate a generator expression after the first sequence of elements
> satisfying a condition, and you don't want to use takewhile, I don't know of a gotcha
> to prevent you from just raising StopIteration, using an expression that will do that, e.g.,
>
>  >>> list (x for x in xrange(20) if x<5 or iter([]).next())
>  [0, 1, 2, 3, 4]
>
> Or a bit more readably:
>  >>> def stop(): raise StopIteration
>  ...
>  >>> list (x for x in xrange(20) if x<5 or stop())
>  [0, 1, 2, 3, 4]
>
> IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or stop()"
If it is a single loop, takewhile/dropwhile is perfectly fine but as I
mentioned in another post, it is nested and the condition needs
surrounding scope so seperate function and StopIteration doesn't work
as it breaks out of the whole thing expression.

takewhile/dropwhile still works in this case(because of the lambda
which sees the surrounding scope).




More information about the Python-list mailing list