Skip to content

Instantly share code, notes, and snippets.

Created January 2, 2013 11:17
Show Gist options
  • Save anonymous/4433900 to your computer and use it in GitHub Desktop.
Save anonymous/4433900 to your computer and use it in GitHub Desktop.
A function returning the first matched item in a sequence, or None.
def first_match(seq, pred=None, default=None):
"""
Obtain the first item in `seq` where `pred` returns True, otherwise return
`default`.
If no `pred` is supplied, then the first value in seq will be returned. If
no `default` is supplied and no matching value is found in `seq`, then
`None` will be returned instead.
:param seq: A sequence or iterable to obtain an item from.
:param pred: A predicate function, taking one argument and returning True
if the item matches the required condition, or
False otherwise.
:param default: The value to be returned if no matching values are obtained
:return: The first matching value, or `default` if no matching values
are found.
"""
if pred is None:
pred = lambda x: True
return next((x for x in seq if pred(x)), default)
@judy2k
Copy link

judy2k commented Jan 2, 2013

I wrote this, if anyone has any questions :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment