Multiple assignment and evaluation order in Python
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 = yspam = x + yx = hamy = spam
By contrast,
x = yy = x + y
sets x
to y
, then sets y
to x
(which == y
) plus y
, so it's equivalent to
x = yy = 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:
- Creates a temporary tuple with value
y,x+y
- Assigned in to another temporary tuple
- Extract the tuple to variables
x
andy
The second statement is actually two expressions, without the tuple usage.
The surprise is, the first expression is actually:
temp=xx=yy=temp+y
You can learn more about the usage of comma in "Parenthesized forms".