In Python, is the a simple way to test that all values in a list are equal to one another?
4 Answers
Many ways come to mind. You could turn it in a Edit: As another poster noted, this only works with hashable types; I revoke the suggestion as it has worse performance and is less general.set
(which filters out duplicates) and check for length of one
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).
-
+1 Using list comprehensions is recommended over map(). – Erik Youngren Jan 20 '11 at 20:56
-
@Artanis: It's not a list comprehension - that's why it's superior to the `set` solution ;) – Jan 20 '11 at 20:58
-
Thanks! this is simple and sweet! – derks Jan 20 '11 at 21:18
-
ah, I missed that it lacked the brackets. Should be a generator then. – Erik Youngren Jan 21 '11 at 01:56
-
i also thought it was a list comprehension, what is it called? Thanks – Drewdin Dec 02 '14 at 20:58
>>> 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.

- 951,095
- 183
- 1,149
- 1,285
>>> l = [1, 1, 1, 1]
>>> all(map(lambda x: x == l[0], l))
True

- 5,746
- 4
- 40
- 57
-
1Note 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
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
.

- 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
-