Multiple assignment and evaluation order in Python Multiple assignment and evaluation order in Python python python

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:

  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=xx=yy=temp+y

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