Find first element in a sequence that matches a predicate
predicate, python
Solution
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)
Problem
I want an idiomatic way to find the first element in a list that matches a predicate. The current code is quite ugly: ``` [x for x in seq if predicate(x)][0] ``` I've thought about changing it to: ``` from itertools import dropwhile dropwhile(lambda x: not predicate(x), seq).next() ``` But there must be something more elegant... And it would be nice if it returns a `None` value rather than raise an exception if no match is found. I know I could just define a function like: ``` def get_first(predicate, seq): for i in seq: if predicate(i): return i return None ``` But it is quite tasteless to start filling the code with utility functions like this (and people will probably not notice that they are already there, so they tend to be repeated over time) if there are built ins that already provide the same.