Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if all elements in a list are the same?

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?

like image 411
Zach Gates Avatar asked Mar 07 '14 03:03

Zach Gates


2 Answers

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.

like image 53
thefourtheye Avatar answered Sep 23 '22 01:09

thefourtheye


Using all and generator expression:

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

Alternative:

mylist.count(mylist[0]) == len(mylist)

NOTE The first will stop as soon as it found there's any different item in the list, while the alternative will not.

like image 37
falsetru Avatar answered Sep 22 '22 01:09

falsetru