converting boolean filter function to lambda

Peter Otten __peter__ at web.de
Thu Jun 25 12:11:33 EDT 2015


Ethan Furman wrote:

> I have the following function:
> 
> def phone_found(p):
>    for c in contacts:
>      if p in c:
>        return True
>    return False
> 
> with the following test data:
> 
> contacts = ['672.891.7280 x999', '291.792.9000 x111']
> main = ['291.792.9001', '291.792.9000']
> 
> which works:
> 
> filter(phone_found, main)
> # ['291.792.9000']
> 
> My attempt at a lambda function fails:
> 
> filter(lambda p: (p in c for c in contacts), main)
> # ['291.792.9001', '291.792.9000']
> 
> Besides using a lambda ;) , what have I done wrong?

The lambda returns a generator expression and that expression is always true 
in a boolean context:

>>> bool(False for _ in ())
True

you're missing any() ...

>>> contacts = ['672.891.7280 x999', '291.792.9000 x111']
>>> main = ['291.792.9001', '291.792.9000']
>>> filter(lambda p: any(p in c for c in contacts), main)
<filter object at 0x7f475ce0e748>

... and list() if you were using Python 3.

>>> list(_)
['291.792.9000']





More information about the Python-list mailing list