Sometimes, we want to check if all elements in a list are identical with Python.
In this article, we’ll look at how to check if all elements in a list are identical with Python.
How to check if all elements in a list are identical with Python?
To check if all elements in a list are identical with Python, we can convert the iterable to a set to see if there’s only 1 element or less.
For instance, we write
def all_equal(iterator):
return len(set(iterator)) <= 1
to convert the iterator
to a set with set
.
Then we get the length of the set with len
and see if it’s 1 or lower.
If there’s only 1 item in the set, then all the elements are equal since sets can’t have duplicates.
If the length is 0, then the iterator
has nothing in it.
Conclusion
To check if all elements in a list are identical with Python, we can convert the iterable to a set to see if there’s only 1 element or less.