Skip to content

Commit a85e512

Browse files
[3.12] Improve all_equal() recipe (gh-116081) (gh-116083)
1 parent dec637a commit a85e512

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
@@ -855,10 +855,9 @@ which incur interpreter overhead.
855855
"Given a predicate that returns True or False, count the True results."
856856
return sum(map(pred, iterable))
857857

858-
def all_equal(iterable):
858+
def all_equal(iterable, key=None):
859859
"Returns True if all the elements are equal to each other."
860-
g = groupby(iterable)
861-
return next(g, True) and not next(g, False)
860+
return len(take(2, groupby(iterable, key))) <= 1
862861

863862
def first_true(iterable, default=False, pred=None):
864863
"""Returns the first true value in the iterable.
@@ -1217,6 +1216,8 @@ The following recipes have a more mathematical flavor:
12171216

12181217
>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
12191218
[True, True, True, False, False]
1219+
>>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
1220+
[True, True, True, False, False]
12201221

12211222
>>> quantify(range(99), lambda x: x%2==0)
12221223
50

0 commit comments

Comments
 (0)