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:
|
|
It’s definitely naturally and elegant. According to the doc:
a, b = b, a
demonstrates that the expressions on the right-hand side are all evaluated first before any of the assignments take place.- 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,
|
|
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
.
|
|
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!
|
|
which returns:
|
|
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
- An Informal Introduction to Python
- http://stackoverflow.com/questions/11502268/how-does-pythons-comma-operator-works-during-assignment
- http://stackoverflow.com/questions/21047524/how-does-swapping-of-members-in-the-python-tuples-a-b-b-a-work-internally
- https://www.quora.com/How-does-Pythons-comma-operator-work-in-assignments-with-expressions