Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all elements in a list are identical

I need a function which takes in a list and outputs True if all elements in the input list evaluate as equal to each other using the standard equality operator and False otherwise.

I feel it would be best to iterate through the list comparing adjacent elements and then AND all the resulting Boolean values. But I'm not sure what's the most Pythonic way to do that.

like image 230
max Avatar asked Oct 02 '10 07:10

max


People also ask

How do you check if all elements are the same in list python?

Here is a simple code with that you can check if all the elements of the list are same using the inbuilt set() method. listChar = ['z','z','z','z'] if(len(set(listChar))==1): print "All elements in list are same." else: print "All elements in list are not same."

How do you check if all items in a list are equal Java?

allMatch() method. The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same.


2 Answers

Use itertools.groupby (see the itertools recipes):

from itertools import groupby  def all_equal(iterable):     g = groupby(iterable)     return next(g, True) and not next(g, False) 

or without groupby:

def all_equal(iterator):     iterator = iter(iterator)     try:         first = next(iterator)     except StopIteration:         return True     return all(first == x for x in iterator) 

There are a number of alternative one-liners you might consider:

  1. Converting the input to a set and checking that it only has one or zero (in case the input is empty) items

    def all_equal2(iterator):     return len(set(iterator)) <= 1 
  2. Comparing against the input list without the first item

    def all_equal3(lst):     return lst[:-1] == lst[1:] 
  3. Counting how many times the first item appears in the list

    def all_equal_ivo(lst):     return not lst or lst.count(lst[0]) == len(lst) 
  4. Comparing against a list of the first element repeated

    def all_equal_6502(lst):     return not lst or [lst[0]]*len(lst) == lst 

But they have some downsides, namely:

  1. all_equal and all_equal2 can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.
  2. all_equal and all_equal3 stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer is False just by looking at the first two elements.
  3. In all_equal2 the content must be hashable. A list of lists will raise a TypeError for example.
  4. all_equal2 (in the worst case) and all_equal_6502 create a copy of the list, meaning you need to use double the memory.

On Python 3.9, using perfplot, we get these timings (lower Runtime [s] is better):

for a list with a difference in the first two elements, groupby is fastestfor a list with no differences, count(l[0]) is fastest

like image 71
kennytm Avatar answered Oct 18 '22 01:10

kennytm


A solution faster than using set() that works on sequences (not iterables) is to simply count the first element. This assumes the list is non-empty (but that's trivial to check, and decide yourself what the outcome should be on an empty list)

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

some simple benchmarks:

>>> timeit.timeit('len(set(s1))<=1', 's1=[1]*5000', number=10000) 1.4383411407470703 >>> timeit.timeit('len(set(s1))<=1', 's1=[1]*4999+[2]', number=10000) 1.4765670299530029 >>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*5000', number=10000) 0.26274609565734863 >>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*4999+[2]', number=10000) 0.25654196739196777 
like image 43
Ivo van der Wijk Avatar answered Oct 18 '22 01:10

Ivo van der Wijk