Proposal: [... for ... while cond(x)]

Duncan Booth duncan.booth at invalid.invalid
Mon Aug 7 03:30:39 EDT 2006


Slawomir Nowaczyk wrote:

> #> No, the list comprehension lets you write an expression directly
> #> avoiding a function call, and it also allows you to add in a
> #> condition which can be used to filer the sequence. 
> 
> I am not sure if I understand you correctly, but... Does it?
> 
>>>> a = [0,1,2,3,7,8,9]
>>>> [x for x in takewhile(lambda x: x in a, range(10))]
> [0, 1, 2, 3]
>>>> [x for x in takewhile(x in a, range(10))]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: 'bool' object is not callable
> 
> Did I miss something?

Yes, you missed out a lambda (so I was wrong, your suggestion would 
actually gain you more than 3 characters of typing)

Try:

>>> a = [0,1,2,3,7,8,9]
>>> [x for x in takewhile(lambda x:x in a, range(10))]
[0, 1, 2, 3]

For this particular expression you could also write:

>>> [x for x in takewhile(a.__contains__, range(10))]
[0, 1, 2, 3]

or with Python 2.5 we can avoid referencing __contains__ with the following 
variant:

>>> from itertools import takewhile
>>> from functools import partial
>>> from operator import contains
>>> a = [0,1,2,3,7,8,9]
>>> [x for x in takewhile(partial(contains,a), range(10))]
[0, 1, 2, 3]
>>>




More information about the Python-list mailing list