I need a function which takes in a list
and outputs True
if all elements in the input list evaluate as equal to each other using the standard equality operator and False
otherwise.
I feel it would be best to iterate through the list comparing adjacent elements and then AND
all the resulting Boolean values. But I'm not sure what's the most Pythonic way to do that.
Best Answer
Use
itertools.groupby
(see theitertools
recipes):or without
groupby
:There are a number of alternative one-liners you might consider:
Converting the input to a set and checking that it only has one or zero (in case the input is empty) items
Comparing against the input list without the first item
Counting how many times the first item appears in the list
Comparing against a list of the first element repeated
But they have some downsides, namely:
all_equal
andall_equal2
can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.all_equal
andall_equal3
stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer isFalse
just by looking at the first two elements.all_equal2
the content must be hashable. A list of lists will raise aTypeError
for example.all_equal2
(in the worst case) andall_equal_6502
create a copy of the list, meaning you need to use double the memory.On Python 3.9, using
perfplot
, we get these timings (lowerRuntime [s]
is better):