Reputation: 308528
I came across this question:
Why does the expression 0 < 0 == 0 return False in Python?
The answers make perfect sense once you understand chained comparisons in Python.
Chained comparisons allow you to write something like 0 < x < 100
which is very convenient for testing to see if something is between 0 and 100. But is there a case where it would even make sense to use ==
or !=
on either side of that comparison? 0 < x == 100
is equivalent to x == 100
for example.
Were ==
and !=
included in the chaining syntax just so that they wouldn't have to be exceptions to the rule, or is there an actual use case?
Upvotes: 3
Views: 112
Reputation: 282104
The most common use case for chaining ==
is chaining it with itself. x == y == z
is a simple way to test that three things are all equal.
Using !=
in a comparison chain is also occasionally useful, but it tends to be less clear. 0 < x != 10
is more concise than 0 < x and x != 10
, but the two comparisons don't feel quite as much like one big comparison as x == y == z
does, and x != y != z
is usually a mistake.
Upvotes: 5