diff options
author | Raymond Hettinger <python@rcn.com> | 2014-04-02 10:16:42 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2014-04-02 10:16:42 (GMT) |
commit | 31b26f637aa118c70157a3e11f58f12620345989 (patch) | |
tree | fd5e7e8d247c548bc2c170e819bbc0acd1084feb /Doc/library/itertools.rst | |
parent | f4284e45d037162835a5a5bc0bc23645b32da26c (diff) | |
download | cpython-31b26f637aa118c70157a3e11f58f12620345989.zip cpython-31b26f637aa118c70157a3e11f58f12620345989.tar.gz cpython-31b26f637aa118c70157a3e11f58f12620345989.tar.bz2 |
Issue #18652: Add an itertools recipe for first_true()
Diffstat (limited to 'Doc/library/itertools.rst')
-rw-r--r-- | Doc/library/itertools.rst | 13 |
1 files changed, 13 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 5d3e50a..f489535 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -784,6 +784,19 @@ which incur interpreter overhead. except exception: pass + def first_true(iterable, default=False, pred=None): + """Returns the first true value in the iterable. + + If no true value is found, returns *default* + + If *pred* is not None, returns the first item + for which pred(item) is true. + + """ + # first_true([a,b,c], x) --> a or b or c or x + # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x + return next(filter(pred, iterable), default) + def random_product(*args, repeat=1): "Random selection from itertools.product(*args, **kwds)" pools = [tuple(pool) for pool in args] * repeat |