[ x for x in xrange(10) when p(x) ]
Alex Martelli
aleax at mail.comcast.net
Fri Nov 11 00:46:37 EST 2005
bonono at gmail.com <bonono at gmail.com> wrote:
> > >>> 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.
Can you give one example where this stop() function wouldn't work and
your hypothetical ``when'' would? I don't see how "it breaks out of the
whole thing expression" -- it terminates ONE for-clause (and what else
would your cherished ``when'' do?).
Alex
More information about the Python-list
mailing list