Possible Duplicate:
Python: find first element in a sequence that matches a predicate
Is there a higher order function in Python standard library that encapsulates the following control flow pattern?
>>> def find(pred, coll):
... for x in coll:
... if pred(x):
... return x
...
>>> find(lambda n : n % 2 == 0, [3, 5, 8, 9, 6])
8
>>> find(lambda n : n % 2 == 0, [3, 5, 7, 9, 6])
6
>>> find(lambda n : n % 2 == 0, [3, 5, 7, 9, 1])
You can combine
ifilterandisliceto get just the first matching element.However, I wouldn’t consider this anyhow more readable or nicer than the original code you posted. Wrapped in a function it will be much nicer though. And since
nextonly returns one element there is no need forisliceanymore:It returns
Noneif no element was found.However, you still have the rather slow call of the predicate function every loop. Please consider using a list comprehension or generator expression instead: