pythonvariable-assignmentassignment-operatormultiple-assignment

Multiple assignment and evaluation order in Python


Suppose we have:

>>> x = 1
>>> y = 2

If we try assigning both values at once like so:

>>> x, y = y, x+y
>>> x
2
>>> y
3

Then we get a different result than if we did the assignments separately:

>>> x = 1
>>> y = 2
>>> x = y
>>> y = x+y
>>> x
2
>>> y
4

Why does this happen?


See also Multiple assignment semantics regarding the effect and purpose of parentheses on the left-hand side of a multiple assignment.

See also Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b? for more complex cases, where the order of assignment matters.


Solution

  • In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables. So,

    x, y = y, x + y
    

    evaluates y (let's call the result ham), evaluates x + y (call that spam), then sets x to ham and y to spam. I.e., it's like

    ham = y
    spam = x + y
    x = ham
    y = spam
    

    By contrast,

    x = y
    y = x + y
    

    sets x to y, then sets y to x (which == y) plus y, so it's equivalent to

    x = y
    y = y + y