[Python Basic] Python Multiple Assignment Is Wonderful. But Did You Know…?
Multiple assignments in Python is just a combination of tuple packing and sequence unpacking.
One of the fascinating features of Python is multiple assignments. For those who know the other programming languages, it must be true. The implementation of a Fibonacci series from the official Python.org shows the beauty of multiple assignments.
To understand the behind story about multiple assignments, we begin with a tuple. A tuple consists of a number of values separated by commas.
The statement t = 12345, 54321, 'hello!'
is an example of tuple packing: the values 12345
, 54321
and 'hello!'
are packed together in a tuple.
The reverse operation is also possible:
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side.
Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.
So the common errors are: too many values to unpack
or not enough values to unpack
Now we can see the beauty of multiple assignment:
Isn’t it beautiful?