Search code examples
pythoncomparison-operators

Python comparison operator precedence


All comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Thus "==" and "<" have the same priority, why would the first expression in the following evaluate to True, different from the 2nd expression?

>>> -1 < 0 == False
True

>>> (-1 < 0) == False
False

I would expect both be evaluated to False. Why is it not the case?


Solution

  • Python has a really nice feature - chained comparison, like in math expressions, so

    -1 < 0 == False
    

    is actually a syntactic sugar for

    -1 < 0 and 0 == False
    

    under the hood.