[ x for x in xrange(10) when p(x) ]
George Sakkis
gsakkis at rutgers.edu
Thu Nov 10 04:58:16 CET 2005
"bonono at gmail.com" wrote:
> Alex Martelli wrote:
> > This becomes a valid list comprehension by writing 'if' instead of
> > 'when'.
>
> valid, yes. efficient, I am not sure.
>
> [ x for x in xrange(10000000) if p(x) ]
>
> means I need to go through the whole range even if p = lambda x: x < 2
Itertools is your friend in this case:
>>> from itertools import takewhile
>>> list(takewhile(p, xrange(10000000)))
[0, 1]
George
More information about the Python-list
mailing list