Apply comparison with a list in Python?

I am trying to compare the elements of a list u

for equality.

A possible solution may all(x == u[0] for x in u[1:])

or may not be simple all(x == u[0] for x in u)

, but it looks rather strange.

Python can be written a == b == c

with its usual "mathematical" meaning. So I decided to write using the operator module operator.eq(*u)

. However, the function eq

only takes two arguments. Of course functools.reduce(operator.eq, u)

not useful here as after the first test eq(u[0], u[1])

I get a boolean and it will fail on the second test eq(<bool>, u[2])

.

Is there a better way than the solution above? Another ... "python" way?

+3


source to share


1 answer


len(set(u)) == 1

pretty Pythonic.



+1


source







All Articles