Back
I need the following function:
Input: a list
Output:
True if all elements in the input list evaluate as equal to each other using the standard equality operator;
False otherwise.
Performance: of course, I prefer not to incur any unnecessary overhead.
I feel it would be best to:
iterate through the list
compare adjacent elements
and AND all the resulting Boolean values
But I'm not sure what's the most Pythonic way to do that.
To check whether all elements in a list are identical or not you can use the following piece of code:-
def checkEqual1(iterator):iterator = iter(iterator)try:first = next(iterator)except StopIteration:return Truereturn all(first == rest for rest in iterator)
def checkEqual1(iterator):
iterator = iter(iterator)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == rest for rest in iterator)
Another thing you can do which is the simplest and most elegant way to solve this problem is as follows:
all(x==myList[0] for x in myList)
31k questions
32.8k answers
501 comments
693 users