Unpacking Tuples in Python
In Python there is a possibility to do unpacking tuples - assign a separate variable to each element. To do this, the variables are listed on the left side of the expression, and the tuple we need is indicated on the right side:
tpl = ('a', 'b', 'c')
txt1, txt2, txt3 = tpl
print(txt1) # 'a'
print(txt2) # 'b'
print(txt3) # 'c'
But there is an important nuance here - the number of variables must match the number of elements in the tuple. Otherwise, an error will be returned:
tpl = ('a', 'b', 'c')
txt1, txt2 = tpl
print(txt1) # will display an error
Given a tuple:
tpl = ('john', 'smit')
Unpack the first and last name into separate variables.
Given a tuple:
tpl = (2, 6, 14)
Unpack the elements into separate variables and find their sum.