tags:

views:

157

answers:

1

Hello,

I would want to do something like:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.find(lambda x: x % 2 == 0)
2
>>> lst.findall(lambda x: x % 2 == 0)
[2, 4]

Is there anything even nearing such behavior in Python's standard libraries ?

P.S. I know it's very easy to roll-your-own here, but I'm looking for a more standartized way

+11  A: 

You can use the filter method:


>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda x: x % 2 == 0, lst)
[2, 4]

or a list comprehension:


>>> lst = [1, 2, 3, 4, 5]
>>> [x for x in lst if x %2 == 0]
[2, 4]

EDIT: for find (single element), you could try:


>>> (x for x in lst if x % 2 == 0).next()
2

Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch. The () brackets make this a generator expression rather than a list comprehension.

Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).

These raise an exception if nothing is found

filter(lambda x: x % 2 == 0, lst)[0]
[x for x in lst if x %2 == 0][0]

These return empty lists

filter(lambda x: x % 2 == 0, lst)[:1]
[x for x in lst if x %2 == 0][:1]
John Montgomery
Thanks! That's for findall. What about find ?
Eli Bendersky
Rather than a generator comprehension, you could also use itertools.ifilter(func, list).next() which is a little closer to the desired syntax.
Brian