3

I am trying to compare elements of a list u for equality.

A possible solution could be all(x == u[0] for x in u[1:]), or simply all(x == u[0] for x in u), but it looks rather weird.

In Python, it's possible to write a == b == c, with its usual "mathematical" meaning. So I thought I could, with the help of the operator module, write operator.eq(*u). However, the eq function takes only two arguments. Of course, functools.reduce(operator.eq, u) is of no use here, since after the first test eq(u[0], u[1]), I get a boolean, and it will fail when doing the second test, eq(<bool>, u[2]).

Is there a better way than the solution above? A more... "pythonic" way?

  • If they’re hashable, you can use `len(set(u)) == 1`, but that’s just shorter, not better. `all` seems straightforward to me. – Ry- Dec 23 '14 at 22:38
  • Argh, I didn't see the duplicate. Thanks @jamylak to have pointed this out. –  Dec 23 '14 at 22:45

1 Answers1

0

len(set(u)) == 1 is pretty Pythonic.

We Are All Monica
  • 13,000
  • 8
  • 46
  • 72
  • 1
    But it returns the wrong answer for an empty input (you should do `<= 1` instead of `== 1`) and it doesn't work if any elements in your list aren't hashable and doesn't short circuit, i.e. if you can tell that the first two elements aren't equal it'll still have to process the whole list. It also requires double the memory (if all the elements in your array are unique). – Boris Verkhovskiy Nov 16 '20 at 01:19