Find first element in a sequence that matches a predicate

fortran picture fortran · Dec 16, 2011 · Viewed 101.5k times · Source

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.

Answer

jfs picture jfs · Dec 16, 2011

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)