Search code examples
pythonsyntax-errorcomparison-operators

Why does equality not appear to be a symmetric relation in Python?


I'm learning about comparison operators, and I was playing around with True and False statements. I ran the following code in the Python shell:

not(5>7) == True

As expected, this returned True. However, I then ran the following code:

True == not(5>7)

and there was a syntax error. Why was this? If the first line of code is valid syntax, then surely the second line of code should also be valid. Where have I gone wrong?

(To give a bit of background, my understanding is that = in Python is only used for variable assignment, while == is closely related to the mathematical symbol '='.)


Solution

  • The syntax error seems to be caused by the not keyword, not (pun intended) the equality operator:

    True == not (5 > 7)
    # SyntaxError: invalid syntax
    
    True == (not (5 > 7))
    # True
    

    The explanation can be found in the docs:

    not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

    Basically, the interpreter thinks you're comparing True to not.