Check if all elements in a list are identical

前端 未结 22 1939
死守一世寂寞
死守一世寂寞 2020-11-22 07:45

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 equal

相关标签:
22条回答
  • 2020-11-22 07:47

    There is also a pure Python recursive option:

    def checkEqual(lst):
        if len(lst)==2 :
            return lst[0]==lst[1]
        else:
            return lst[0]==lst[1] and checkEqual(lst[1:])
    

    However for some reason it is in some cases two orders of magnitude slower than other options. Coming from C language mentality, I expected this to be faster, but it is not!

    The other disadvantage is that there is recursion limit in Python which needs to be adjusted in this case. For example using this.

    0 讨论(0)
  • 2020-11-22 07:48

    The simplest and most elegant way is as follows:

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

    (Yes, this even works with the empty list! This is because this is one of the few cases where python has lazy semantics.)

    Regarding performance, this will fail at the earliest possible time, so it is asymptotically optimal.

    0 讨论(0)
  • 2020-11-22 07:48

    This is a simple way of doing it:

    result = mylist and all(mylist[0] == elem for elem in mylist)
    

    This is slightly more complicated, it incurs function call overhead, but the semantics are more clearly spelled out:

    def all_identical(seq):
        if not seq:
            # empty list is False.
            return False
        first = seq[0]
        return all(first == elem for elem in seq)
    
    0 讨论(0)
  • 2020-11-22 07:50

    A set comparison work:

    len(set(the_list)) == 1
    

    Using set removes all duplicate elements.

    0 讨论(0)
  • 2020-11-22 07:51

    You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element.

    if len(set(input_list)) == 1:
        # input_list has all identical elements.
    
    0 讨论(0)
  • 2020-11-22 07:52

    Or use diff method of numpy:

    import numpy as np
    def allthesame(l):
        return np.all(np.diff(l)==0)
    

    And to call:

    print(allthesame([1,1,1]))
    

    Output:

    True
    
    0 讨论(0)
提交回复
热议问题