Multiple assignment and evaluation order in Python

An observation regarding the left-hand side as well: the order of assignments is guaranteed to be the order of their appearance, in other words:

a, b = c, d

is equivalent functionally to precisely (besides t creation):

t = (c, d)
a = t[0] # done before 'b' assignment
b = t[1] # done after 'a' assignment

This matters in cases like object attribute assignment, e.g.:

class dummy:
    def __init__(self): self.x = 0

a = dummy(); a_save = a
a.x, a = 5, dummy()
print(a_save.x, a.x) # prints "5 0" because above is equivalent to "a = dummy(); a_save = a; t = (5, dummy()); a.x = t[0]; a = t[1]"

a = dummy(); a_save = a
a, a.x = dummy(), 5
print(a_save.x, a.x) # prints "0 5" because above is equivalent to "a = dummy(); a_save = a; t = (dummy(), 5); a = t[0]; a.x = t[1]"

This also implies that you can do things like object creation and access using one-liners, e.g.:

class dummy:
    def __init__(self): self.x = 0
# Create a = dummy() and assign 5 to a.x
a, a.x = dummy(), 5

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

It is explained in the docs in the section entitled "Evaluation order":

... while evaluating an assignment, the right-hand side is evaluated before the left-hand side.


The first expression:

  1. Creates a temporary tuple with value y,x+y
  2. Assigned in to another temporary tuple
  3. Extract the tuple to variables x and y

The second statement is actually two expressions, without the tuple usage.

The surprise is, the first expression is actually:

temp=x
x=y
y=temp+y

You can learn more about the usage of comma in "Parenthesized forms".