Python – How to Check if All Elements in a List Are the Same

listpythonpython-2.7

If i have this list;

mylist = ['n', 'n', '4', '3', 'w']

How do I get it to read the list, and tell me whether or not they are all the same?

I am aware that it is easy to tell they are not all the same in this example. I have much larger lists I would like it to read for me.

Would I go about this using:

min(...)

If so, how would I input each list item?

Best Answer

You can use set like this

len(set(mylist)) == 1

Explanation

sets store only unique items in them. So, we try and convert the list to a set. After the conversion, if the set has more than one element in it, it means that not all the elements of the list are the same.

Note: If the list has unhashable items (like lists, custom classes etc), the set method cannot be used. But we can use the first method suggested by @falsetru,

all(x == mylist[0] for x in mylist)

Advantages:

  1. It even works with unhashable types

  2. It doesn't create another temporary object in memory.

  3. It short circuits after the first failure. If the first and the second elements don't match, it returns False immediately, whereas in the set approach all the elements have to be compared. So, if the list is huge, you should prefer the all approach.

  4. It works even when the list is actually empty. If there are no elements in the iterable, all will return True. But the empty list will create an empty set for which the length will be 0.

Related Question