George Sakkis wrote: > "[EMAIL PROTECTED]" 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]
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. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list