next(x for x in lst if matchCondition(x))
should work, but it will raise StopIteration
if none of the elements in the list match. You can suppress that by supplying a second argument to next
:
next((x for x in lst if matchCondition(x)), None)
which will return None
if nothing matches.
Demo:
>>> next(x for x in range(10) if x == 7) #This is a silly way to write 7 ...
7
>>> next(x for x in range(10) if x == 11)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> next((x for x in range(10) if x == 7), None)
7
>>> print next((x for x in range(10) if x == 11), None)
None
Finally, just for completeness, if you want all the items that match in the list, that is what the builtin filter
function is for:
all_matching = filter(matchCondition,lst)
In python2.x, this returns a list, but in python3.x, it returns an iterable object.