python assign to tuple code example
Example 1: what are tuples
Tuples in Python
An immutable data value that contains related elements.
Tuples are used to group together related data,
such as a person’s name, their age, and their gender.
A tuple is the same as a list except uses parenthisies instead of square brackets.
A tuple is also immutable (cant be changed) unlike a list.
Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
Example 2: 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'