Skip to content

[3.12] Improve all_equal() recipe (gh-116081) #116083

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -855,10 +855,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.
Expand Down Expand Up @@ -1217,6 +1216,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
Expand Down