tuple assignment python

Solutions on MaxInterview for tuple assignment python by the best coders in the world

showing results for - "tuple assignment python"
Clifton
09 Aug 2018
1Python 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.
2
3Example:
4(name, surname, b_year, movie, m_year, profession, b_place) = julia
5This does the equivalent of seven assignment statements, all on one easy line. 
6One requirement is that the number of variables on the left must match the number of elements in the tuple.
7
8One way to think of tuple assignment is as tuple packing/unpacking.
9
10In tuple packing, the values on the left are ‘packed’ together in a tuple:
11
12>>> b = ("Bob", 19, "CS")    # tuple packing
13In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names on the right:
14
15>>> b = ("Bob", 19, "CS")
16>>> (name, age, studies) = b    # tuple unpacking
17>>> name
18'Bob'
19>>> age
2019
21>>> studies
22'CS'