summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2024-02-28 23:04:56 (GMT)
committerGitHub <noreply@github.com>2024-02-28 23:04:56 (GMT)
commit67c19e57b5c928278ebd191a545979ce786f06b3 (patch)
tree89cb3b560a1f1cc29d8dbe1508e52e40e9c7b394 /Doc
parent81c79961d2ee27dec90dbc0b72dfca7a5b27de7a (diff)
downloadcpython-67c19e57b5c928278ebd191a545979ce786f06b3.zip
cpython-67c19e57b5c928278ebd191a545979ce786f06b3.tar.gz
cpython-67c19e57b5c928278ebd191a545979ce786f06b3.tar.bz2
Improve all_equal() recipe (gh-116081)
Replace conjuction of next() calls with simpler len()/take() logic. Add key function.
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/itertools.rst7
1 files changed, 4 insertions, 3 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 42e7040..4e731fe 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -863,10 +863,9 @@ which incur interpreter overhead.
"Given a predicate that returns True or False, count the True results."
return sum(map(pred, iterable))
- def all_equal(iterable):
+ def all_equal(iterable, key=None):
"Returns True if all the elements are equal to each other."
- g = groupby(iterable)
- return next(g, True) and not next(g, False)
+ return len(take(2, groupby(iterable, key))) <= 1
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
@@ -1225,6 +1224,8 @@ The following recipes have a more mathematical flavor:
>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
[True, True, True, False, False]
+ >>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
+ [True, True, True, False, False]
>>> quantify(range(99), lambda x: x%2==0)
50