Search code examples
pythonoperator-precedencecomparison-operators

How does python operator precedence work with double comparisons?


-3<-2<-1 returns True.

However I would expect it interpreted as

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

How is that possible ?


Solution

  • 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.