Python - Check if all elements in a list are identical

There may be occasions when a list contains all identical values. In this article we will see various ways to verify that all elements in a list are the same.

Using all() Function

We use the all() function to compare each element of the list with the first element. If each comparison returns True, then all elements are identical ?

days_a = ['Sun', 'Sun', 'Mon']

result_a = all(x == days_a[0] for x in days_a)

if result_a:
    print("In days_a all elements are same")
else:
    print("In days_a all elements are not same")
    
days_b = ['Sun', 'Sun', 'Sun']
result_b = all(x == days_b[0] for x in days_b)

if result_b:
    print("In days_b all elements are same")
else:
    print("In days_b all elements are not same")
In days_a all elements are not same
In days_b all elements are same

Using count() Method

In this approach we count the occurrences of the first element and compare it with the length of the list. If all elements are identical, the count will equal the list length ?

days_a = ['Sun', 'Sun', 'Mon']

result_a = days_a.count(days_a[0]) == len(days_a)

if result_a:
    print("In days_a all elements are same")
else:
    print("In days_a all elements are not same")

days_b = ['Sun', 'Sun', 'Sun']
result_b = days_b.count(days_b[0]) == len(days_b)

if result_b:
    print("In days_b all elements are same")
else:
    print("In days_b all elements are not same")
In days_a all elements are not same
In days_b all elements are same

Using set() for Unique Elements

Converting the list to a set removes duplicates. If all elements are identical, the set will have only one element ?

days_a = ['Sun', 'Sun', 'Mon']
days_b = ['Sun', 'Sun', 'Sun']

result_a = len(set(days_a)) == 1
result_b = len(set(days_b)) == 1

print(f"In days_a all elements are same: {result_a}")
print(f"In days_b all elements are same: {result_b}")
In days_a all elements are same: False
In days_b all elements are same: True

Comparison

Method Time Complexity Best For
all() O(n) Readable, stops early on mismatch
count() O(n) Simple logic
set() O(n) Handles unhashable types poorly

Conclusion

Use all() for the most readable and efficient solution as it stops checking once a mismatch is found. The set() method is concise but may not work with unhashable types like lists.

Updated on: 2026-03-15T18:15:18+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements