assignment tuple python code example
Example: tuple assignment python
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an assignment to be assigned values from a tuple on the right of the assignment. (We already saw this used for pairs, but it generalizes.
Example:
(name, surname, b_year, movie, m_year, profession, b_place) = julia
This does the equivalent of seven assignment statements, all on one easy line.
One requirement is that the number of variables on the left must match the number of elements in the tuple.
One way to think of tuple assignment is as tuple packing/unpacking.
In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>> b = ("Bob", 19, "CS")
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names on the right:
>>> b = ("Bob", 19, "CS")
>>> (name, age, studies) = b
>>> name
'Bob'
>>> age
19
>>> studies
'CS'