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
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,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 theset
approach all the elements have to be compared. So, if the list is huge, you should prefer theall
approach.It works even when the list is actually empty. If there are no elements in the iterable,
all
will returnTrue
. But the empty list will create an emptyset
for which the length will be 0.