Search code examples
pythonoperator-precedence

How is x += 1 <= y evaluated in Python?


How is x += 1 <= y evaluated in Python?

Intuitively I assume it is x += (1 <= 2) but it seems to be (x += 1) <= 2, however without any return value and x += 1 returning the value of x before the operation is executed. An explanation would be great!

Thanks!


Solution

  • No, the assignment operators have lower precedence than the comparison operators, so it is evaluated as x += (1 <= y).

    >>> x = 3
    >>> y = 7
    >>> x += 1 <= y
    >>> x
    4
    

    1 <= y is True, which has the value 1, and 1 is added to x.

    Python does not treat assignment operators like C. You cannot use them in mid-expression, so:

    >>> z = (x+=1) + (x+=1)
      File "<stdin>", line 1
        z = (x+=1) + (x+=1)
               ^
    SyntaxError: invalid syntax