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?
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:
It even works with unhashable types
It doesn't create another temporary object in memory.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With