StopIteration in the if clause of a generator expression

Raymond Hettinger vze4rx4y at verizon.net
Fri Apr 1 19:21:09 EST 2005


> I assumed that all standard sequence consumers (including list, of course)
would intercept
> the StopIteration of a sequence given them in the form of a generator
expression, so your
> lyst example would have an analogue for other sequence consumers as well,
right?
> I.e., there's not a hidden list(genex) in those others I would hope ;-)

Right.



> E.g., "in" in my toy exposed more clearly, using Peter's stop:
>
>  >>> def show(x): print x,; return x
>  ...
>  >>> def stop(): raise StopIteration
>  ...
>  >>> 2 in (x for x in xrange(5) if show(x)<4 or stop())
>  0 1 2
>  True
>  >>> 7 in (x for x in xrange(5) if show(x)<4 or stop())
>  0 1 2 3 4
>  False
>
> BTW I notice that this also nicely shortcuts when the 2 is found.

That's a fact.


Raymond





More information about the Python-list mailing list