23

In Python, is the a simple way to test that all values in a list are equal to one another?

derks
  • 546
  • 1
  • 4
  • 7

4 Answers4

42

Many ways come to mind. You could turn it in a set (which filters out duplicates) and check for length of oneEdit: As another poster noted, this only works with hashable types; I revoke the suggestion as it has worse performance and is less general.

You could use a generator expression: all(items[0] == item for item in items), which would short-circuit (i.e. return false as soon as the predicate fails for an item instead of going on).

13
>>> a = [1, 1, 1, 1]
>>> len(set(a))
1

Note that this method assumes that each element in your list can be placed into a set. Some types, such as the mutable types, cannot be placed into a set.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
3
>>> l = [1, 1, 1, 1]
>>> all(map(lambda x: x == l[0], l))
True
Mariy
  • 5,746
  • 4
  • 40
  • 57
  • 1
    Note that this iterates through the while list unconditionally (there are several equally simple solutions that don't). –  Jan 20 '11 at 20:42
  • `map` is an iterator in Python 3, so `all` won't iterate past the first unequal value. Or in Python 2, use `functools.imap`. – PaulMcG Feb 13 '13 at 22:19
1

Using a set as pointed out by Greg Hewgill is a great solution. Here's another one that's more lazy, so if one pair of the elements are not equal, the rest will not be compared. This might be slower than the set solution when comparing all items, but didn't benchmark it.

l = [1, 1, 1]
all(l[i] == l[i+1] for i in range(len(l)-1))

Note the special case all([]) == True.

AndiDog
  • 68,631
  • 21
  • 159
  • 205
  • This will compare each item with the next one (and raise an out of range error for odd-length inputs). –  Jan 20 '11 at 20:59
  • @delnan: Yes it might be better to just take the first element (if there's one) and compare it to all others. But what do you mean by odd-length input? – AndiDog Jan 20 '11 at 21:10
  • A `l` for which `n = len(l)` is odd that doesn't terminate erlier will try to access `l[n-1+1] = l[n]`, which is out of range. –  Jan 21 '11 at 13:49
  • 1
    @delnan: Isn't that exactly what the example in my answer shows? I'm using `range(len(l)-1)`, i.e. the range will go from 0 to `len(l)-2`, so I don't think your objection is correct?! – AndiDog Jan 21 '11 at 13:53
  • Yes, nevermind (it's incorrect, but it won't crash). –  Jan 21 '11 at 14:00