In this article we will dicuss different ways to check if all element in a given List are same or matches a condition.

Suppose we have a list of string i.e.

Now let’s use python all() function to check if all elements in the given list are same.

Python : all() function

Python all() function checks if all Elements of given Iterable is True.

check if element are same using all()

Let’s convert the list to Iterable and check if each entry of iterable is equal to first element of list using all() i.e.

Check if all elements are same using list.count()

count() returns the occurrence count of given element in the list.

Let’s call the count() function of list with firts element of list as argument. If its occurrence count is equal to the length of list, then it means all elements in list are Same i.e.

Let’s do the same thing in single line i.e.

Check if all elements are same using Set

As set contains only unique elements, so convert the list to set. If set size is 1 then it means all elements in given list are same i.e.

Complete example is as follows,




Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.