Categories

How to check if all elements in a list are identical in Python?

Sometimes, we want to check if all elements in a list are identical in Python.

In this article, we’ll look at how to check if all elements in a list are identical in Python.

How to check if all elements in a list are identical in Python?

To check if all elements in a list are identical in Python, we can convert the list to a set and check whether the set’s length is 1 or shorter.

For instance, we write:

``````the_list = [1, 1, 1, 1, 1]

all_same = len(set(the_list)) <= 1
print(all_same)
``````

We define the `the_list` list with all 1’s.

Then we call `set` with `the_list` to convert it to a set.

Next, we get the length of the set with `len`.

And we check that the set’s length is 1 or less than return that.

Finally, we assign the result to `all_same`.

Therefore, `all_same` is `True`.

Conclusion

To check if all elements in a list are identical in Python, we can convert the list to a set and check whether the set’s length is 1 or shorter.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.