Python – Check if all elements in a List are the same
In this tutorial, we are going to see different ways to check if all the items in a given list are the same.
- Using Set
- Using all() method
- Using count() method
Check if all elements in a List are the same using Set
Set is a type of collection in Python, just like list and tuple. Set is different because the elements do not have duplicates, unlike list and tuple. All the elements of the set are unique.
Here is a simple program with which you can check if all the items in the list are the same.
listOfColor = ['blue','blue','blue','blue'] if(len(set(listOfColor))==1): print("All items in the list are the same") else: print("All items in the list are not the same")
Output:
All items in the list are the same
Check if all elements in a List are the same using all() method
The all() function is a function that takes an iterable as input and returns “true” if all elements of that input are “true”. Otherwise, “false”.
The easiest way is to check if all the items in the list are the same as the first item in the list.
listOfColor = ['blue','blue','blue','blue'] if all(x == listOfColor[0] for x in listOfColor): print("All items in the list are the same") else: print("All items in the list are not the same")
Output:
All items in the list are the same
Check if all elements in a List are the same using count() method
count() returns the number of occurrences of a given item in the list.
We call the count() function on the list with the first element of the list as an argument. If its number of occurrences is equal to the length of the list, it means that all the elements of the list are the same.
listOfColor = ['blue','blue','blue','blue'] if listOfColor.count(listOfColor[0]) == len(listOfColor): print("All items in the list are the same") else: print("All items in the list are not the same")
Output:
All items in the list are the same