Skip to content

Commit e525ee3

Browse files
committed
Document another recipe for itertools: all_equal(). Inspired by David Beazley.
1 parent d66dd5c commit e525ee3

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

Doc/library/itertools.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,11 @@ which incur interpreter overhead.
693693
"Returns the nth item or a default value"
694694
return next(islice(iterable, n, None), default)
695695

696+
def all_equal(iterable):
697+
"Returns True if all the elements are equal to each other"
698+
g = groupby(iterable)
699+
return next(g, True) and not next(g, False)
700+
696701
def quantify(iterable, pred=bool):
697702
"Count how many times the predicate is true"
698703
return sum(map(pred, iterable))

Lib/test/test_itertools.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2014,6 +2014,11 @@ def test_permutations_sizeof(self):
20142014
... "Returns the nth item or a default value"
20152015
... return next(islice(iterable, n, None), default)
20162016
2017+
>>> def all_equal(iterable):
2018+
... "Returns True if all the elements are equal to each other"
2019+
... g = groupby(iterable)
2020+
... return next(g, True) and not next(g, False)
2021+
20172022
>>> def quantify(iterable, pred=bool):
20182023
... "Count how many times the predicate is true"
20192024
... return sum(map(pred, iterable))
@@ -2127,6 +2132,9 @@ def test_permutations_sizeof(self):
21272132
>>> nth('abcde', 9) is None
21282133
True
21292134
2135+
>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
2136+
[True, True, True, False, False]
2137+
21302138
>>> quantify(range(99), lambda x: x%2==0)
21312139
50
21322140

0 commit comments

Comments
 (0)