I have a function. matchCondition(a), which takes an integer and either returns True or False.
I have a list of 10 integers. I want to return the first item in the list (in the same order as the original list) that has matchCondition returning True.
As pythonically as possible.
should work, but it will raise
StopIterationif none of the elements in the list match. You can suppress that by supplying a second argument tonext:which will return
Noneif nothing matches.Demo:
Finally, just for completeness, if you want all the items that match in the list, that is what the builtin
filterfunction is for:In python2.x, this returns a list, but in python3.x, it returns an iterable object.