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

George Sakkis gsakkis at rutgers.edu
Thu Nov 10 02:37:16 EST 2005


"Steve Holden" <steve at holdenweb.com> wrote:

> George Sakkis wrote:
> > Itertools is your friend in this case:
> >
> >>>>from itertools import takewhile
> >>>>list(takewhile(p, xrange(10000000)))
> >
> > [0, 1]
>
> Maybe, but the code also implies an esoteric knowledge that the trught
> value of the predicate is monotonically decreasing (in a Boolean sense).
> This would not be true if (e.g.) p = lambda x: x % 2 == 0. So while
> itertools.takewhile can save you unnecessary computations, such savings
> rely on provable conditions of the predicate which are frequently false.

Right, it wasn't intended as a general solution for any p. For p =
lambda x: x % 2 == 0, you do have to iterate till the iterator is
consumed anyway, so a list comprehension is not less efficient (unless
you replaced it with xrange(0,10000000,2), which again implies an
esoteric knowledge of p; as usually, there's no free meal).

George




More information about the Python-list mailing list