how does multiple assignment work internally

Learning the pythonic way to code makes your code elegant and easy to understand. Since it’s a different coding style among other languages, coder like me should understand completely about the underlying mechanism. In this post, we will talk about multiple assignment, a.k.a. tuple assignment.

1. Multiple Assignment

As a reminder, we swap two variables by using the following line:

1
a, b = b, a

It’s definitely naturally and elegant. According to the doc:

  1. a, b = b, a demonstrates that the expressions on the right-hand side are all evaluated first before any of the assignments take place.
  2. The right-hand side expressions are evaluated from the left to the right.

From above we can learn the basic principles of multiple assignment. Thus,

1
2
3
4
a, b = 1, 3
a, b = a+b, a
a, b = 1+3, 1

2. Tuple Abbreviation

Python lets users abbreviate tuples. For example, x = (1, 2) can be written as x = 1, 2. So multiple assignment is just a special case of tuple abbreviation. Note that Python does not have a comma operator. I think it’s pretty convenient using multiple assignment with tuple comprehensions.

1
2
a, b, c, d = (i*i for i in range(0,7) if i % 2 == 0)
# returns a=0, b=4, c=16, d=36

Also, remember to avoid error like “too many values to unpack”.

What if, you want to see things going on internally? Using dis module can help us to find out!

1
2
3
4
5
import dis
def (a, b):
... a, b = a+b, a
...
dis.dis(foo)

which returns:

1
2
3
4
5
6
7
8
9
>>> dis.dis(swap)
2 0 LOAD_FAST 1 (a)
3 LOAD_FAST 0 (b)
6 BINARY_ADD
7 LOAD_FAST 0 (a)
10 ROT_TWO
11 STORE_FAST 0 (a)
14 STORE_FAST 1 (b)
17 RETURN_VALUE

I think it explains everything itself. And it’s consist with the basic principles mentioned above.If you want to know meanings of these term, check this link.

3. Acknowledgment

  1. An Informal Introduction to Python
  2. http://stackoverflow.com/questions/11502268/how-does-pythons-comma-operator-works-during-assignment
  3. http://stackoverflow.com/questions/21047524/how-does-swapping-of-members-in-the-python-tuples-a-b-b-a-work-internally
  4. https://www.quora.com/How-does-Pythons-comma-operator-work-in-assignments-with-expressions