Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (7.3k points)

I need the following function:

Input: a list


  • 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.

1 Answer

0 votes
by (106k points)

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)


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)

Related questions

Browse Categories