Skip to content
Related Articles

Related Articles

Python | Check if all elements in a list are identical

Improve Article
Save Article
  • Last Updated : 27 Sep, 2022
Improve Article
Save Article

Given a list, write a Python program to check if all the elements in that list are identical using Python

Examples:

Input : ['a', 'b', 'c']
Output : False

Input : [1, 1, 1, 1]
Output : True

Check if all elements in a list are identical or not using a loop 

Start a Python for loop and check if the first element is identical to all other elements in the list. This approach takes O(n) time complexity.

Python3




# Python3 program to check if
# all elements in a list are identical
def check(list):
    return all(i == list[0] for i in list)
     
# Driver code
print(check(['a', 'b', 'c']))
print(check([1, 1, 1]))


Output:

False
True

Check if all elements in a list are identical or not using set()

Set Converting the given list into Python set. It removes all duplicate elements, If the resultant set size is less than or equal to 1 then the list contains all identical elements. 

Python3




# Python3 program to check if
# all elements in a list are identical
def check(list):
   return len(set(list)) == 1
    
# Driver code
print(check(['a', 'b', 'c']))
print(check([1, 1, 1]))


Output:

False
True

Check if all elements in a list are identical or not using count() 

By counting the number of times the first element occurs in the list, we can check if the count is equal to the size of the list or not. In simple words, check if the first element is repeated throughout the list or not. 

Python3




def check(list):
   return list.count(list[0]) == len(list)
    
# Driver code
print(check(['a', 'b', 'c']))
print(check([1, 1, 1]))


Output:

False
True

Check if all elements in a list are identical or not using the length

Another method is to take the first element and multiply it by the length of the given list to form a new list, So that the new list contains identical elements to the first elements of the given list size, and then compare it with the given list. 

Python3




def check(x):
    return x and [x[0]]*len(x) == x
    
# Driver code
print(check(['a', 'b', 'c']))
print(check([1, 1, 1]))


Output:

False
True

Check if all elements in a list are identical or not using slicing

Python slice notation is used to retrieve a subset of values. Thus, we compare the start to the end of the list to the end to the start of the list. 

Python3




def check(list):
   return list[1:] == list[:-1]
    
# Driver code
print(check(['a', 'b', 'c']))
print(check([1, 1, 1]))


Output:

False
True

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!