0

Possible Duplicate:
check if all elements in a list are identical

I want to check if all of the elements of a list are equal. I couldn't do this with:

if all (x == x for x in (a, b, c, d)):
    ...

Is there very minimalistic and elegant way to do this in Python?

Community
  • 1
  • 1
Berk Özbalcı
  • 3,016
  • 3
  • 21
  • 27

4 Answers4

5

If you have only hashable elements in your list you can use a set.

For example if your list is named lst you can do:

if (len(set(lst)) <= 1):
    ....

The set will eliminate all the duplicates in your list, so if the length of the set is 1 it means that all the elements are the same.

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
3
all(x == items[0] for x in items)

this is what you're looking for.

Otherwise you would be comparing every value to itself x==x as opposed to every value to the first value.

John
  • 13,197
  • 7
  • 51
  • 101
0
first = my_list[0]
print all(x==first for x in my_list[1:])

should work

more elegant maybe ... (I dont really think so...)

>>> if reduce(lambda item0,item1:item0 if item0==item1 else False,my_list) is not False:
...    print "OK ALL THE SAME!"
...
OK ALL THE SAME!
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
-2

answered here , with performance benchmark

my favorite : lst[1:] == lst[:-1]

Community
  • 1
  • 1
lucasg
  • 10,734
  • 4
  • 35
  • 57