I would like to get the first item from a list matching a condition. It's important that the resulting method not process the entire list, which could be quite large. For example, the following function is adequate:
def first(the_iterable, condition = lambda x: True):
for i in the_iterable:
if condition(i):
return i
This function could be used something like this:
>>> first(range(10))
0
>>> first(range(10), lambda i: i > 3)
4
However, I can't think of a good built-in / one-liner to let me do this. I don't particularly want to copy this function around if I don't have to. Is there a built-in way to get the first item matching a condition?
Similar to using
ifilter
, you could use a generator expression:In either case, you probably want to catch
StopIteration
though, in case no elements satisfy your condition.Technically speaking, I suppose you could do something like this:
It would avoid having to make a
try/except
block. But that seems kind of obscure and abusive to the syntax.Since you've requested a built-in one-liner, this will avoid the issue of a
StopIteration
exception, though it requires that your iterable is small so you can cast it to a list, since that is the only construct I know of which will swallow a StopIteration and let you peek at the values:(If no element matches, you will get
None
rather than aStopIteration
exception.)In Python 3:
In Python 2.6:
EDIT: I thought it was obvious, but apparently not: instead of
None
you can pass a function (or alambda
) with a check for the condition:Oneliner:
If youre not sure that any element will be valid according to the criteria, you should enclose this with
try/except
since that[0]
can raise anIndexError
.Damn Exceptions!
I love this answer. However, since
next()
raise aStopIteration
exception when there are no items, i would use the following snippet to avoid an exception:For example,
Will raise a
StopIteration
exception;I would write this