Skip to content

Commit 67c19e5

Browse files
authored
Improve all_equal() recipe (gh-116081)
Replace conjuction of next() calls with simpler len()/take() logic. Add key function.
1 parent 81c7996 commit 67c19e5

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

Doc/library/itertools.rst

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -863,10 +863,9 @@ which incur interpreter overhead.
863863
"Given a predicate that returns True or False, count the True results."
864864
return sum(map(pred, iterable))
865865

866-
def all_equal(iterable):
866+
def all_equal(iterable, key=None):
867867
"Returns True if all the elements are equal to each other."
868-
g = groupby(iterable)
869-
return next(g, True) and not next(g, False)
868+
return len(take(2, groupby(iterable, key))) <= 1
870869

871870
def first_true(iterable, default=False, pred=None):
872871
"""Returns the first true value in the iterable.
@@ -1225,6 +1224,8 @@ The following recipes have a more mathematical flavor:
12251224

12261225
>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
12271226
[True, True, True, False, False]
1227+
>>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
1228+
[True, True, True, False, False]
12281229

12291230
>>> quantify(range(99), lambda x: x%2==0)
12301231
50

0 commit comments

Comments
 (0)