-3<-2<-1
returns True
.
However I would expect it interpreted as
(-3<-2)<-1
True<-1
1<-1
False
How is that possible ?
-3<-2<-1
returns True
.
However I would expect it interpreted as
(-3<-2)<-1
True<-1
1<-1
False
How is that possible ?
This is a chained comparison. Instead of being left-associative like (-3 < -2) < -1
or right-associative like -3 < (-2 < -1)
, it's actually treated as
(-3 < -2) and (-2 < -1)
except that -2
is evaluated at most once.
Unlike C, expressions like
a < b < c
have the interpretation that is conventional in mathematicsComparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to befalse
).
Therefore
-3 < -2 < -1
is equivalent to
-3 < -2 and -2 < -1 # where -2 is evaluated only once