Created
January 2, 2013 11:17
-
-
Save anonymous/4433900 to your computer and use it in GitHub Desktop.
A function returning the first matched item in a sequence, or None.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this, if anyone has any questions :)