To find the first element in a sequence seq
that matches a predicate
:
next(x for x in seq if predicate(x))
Or simply:
Python 2:
next(itertools.ifilter(predicate, seq))
Python 3:
next(filter(predicate, seq))
These will raise a StopIteration
exception if the predicate does not match for any element.
To return None
if there is no such element:
next((x for x in seq if predicate(x)), None)
Or:
next(filter(predicate, seq), None)