Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python operator precedence work with double comparisons? [duplicate]

-3<-2<-1 returns True.

However I would expect it interpreted as

(-3<-2)<-1
True<-1
1<-1
False

How is that possible ?

like image 598
fffred Avatar asked Sep 02 '26 11:09

fffred


2 Answers

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.

like image 167
user2357112 supports Monica Avatar answered Sep 04 '26 00:09

user2357112 supports Monica


From the docs:

Unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Therefore

-3 < -2 < -1  

is equivalent to

-3 < -2 and -2 < -1  # where -2 is evaluated only once
like image 31
TemporalWolf Avatar answered Sep 04 '26 00:09

TemporalWolf