Check if all elements in a list are identical

前端 未结 22 2217
死守一世寂寞
死守一世寂寞 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: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)
    

提交回复
热议问题