Search code examples
pythonpython-3.xequalityoperator-precedenceboolean-expression

Python: real order of execution for equalities/inequalities in expressions?


Imagine this "sneaky" python code:

>>> 1 == 2 < 3
False

According to Python documentation all of the operators in, not in, is, is not, <, <=, >, >=, !=, == have the same priority, but what happens here seems contradictory.

I get even weirder results after experimenting:

>>> (1 == 2) < 3
True
>>> 1 == (2 < 3)
True

What is going on?

(Note)

>>> True == 1
True
>>> True == 2
False
>>> False == 0
True
>>> False == -1
False

Boolean type is a subclass of int and True represents 1 and False represents 0.

This is likely an implementation detail and may differ from version to version, so I'm mostly interested in python 3.10.


Solution

  • Python allows you to chain conditions, it combines them with and. So

    1 == 2 < 3
    

    is equivalent to

    1 == 2 and 2 < 3
    

    This is most useful for chains of inequalities, e.g. 1 < x < 10 will be true if x is between 1 and 10.

    WHen you add parentheses, it's not a chain any more. So

    (1 == 2) < 3
    

    is equivalent to

    False < 3
    

    True and False are equivalent to 0 and 1, so False < 3 is the same as 0 < 3, which is True.

    Similarly,

    1 == (2 < 3)
    

    is equivalent to

    1 == True
    

    which is equivalent to

    1 == 1
    

    which is obviously True.