How do chained assignments work?

Left first

x = y = some_function()

is equivalent to

temp = some_function()
x = temp
y = temp

Note the order. The leftmost target is assigned first. (A similar expression in C may assign in the opposite order.) From the docs on Python assignment:

…assigns the single resulting object to each of the target lists, from left to right.

Disassembly shows this:

>>> def chained_assignment():
...     x = y = some_function()
...
>>> import dis
>>> dis.dis(chained_assignment)
  2           0 LOAD_GLOBAL              0 (some_function)
              3 CALL_FUNCTION            0
              6 DUP_TOP
              7 STORE_FAST               0 (x)
             10 STORE_FAST               1 (y)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

CAUTION: the same object is always assigned to each target. So as @Wilduck and @andronikus point out, you probably never want this:

x = y = []   # Wrong.

In the above case x and y refer to the same list. Because lists are mutable, appending to x would seem to affect y.

x = []   # Right.
y = []

Now you have two names referring to two distinct empty lists.

Leave a Comment