To find first element in a sequence seq
that matches a predicate
:
next(x for x in seq if predicate(x))
Or (itertools.ifilter
on Python 2):
next(filter(predicate, seq))
It raises StopIteration
if there is none.
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)