Python Forum

Full Version: Tuple Unpacking
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can anyone help me with Tuple unpacking term? If given example, that will help me to understand more clearly.
Let's say you have tuple:
person = ('Daniel', 18, 'chess')
then you can unpack these tuple values by assigning them to variables (number of variables must be the same as number of values in tuple), like this (tuple unpacking):
name, age, hobby = person
and the variables values are now:
print('Name: {}, age: {}, hobby: {}'.format(name, age, hobby))
Output:
Name: Daniel, age: 18, hobby: chess
(Jan-23-2019, 02:10 PM)mlieqo Wrote: [ -> ](number of variables must be the same as number of values in tuple)
Just to expand a bit. Above is correct, but in python3 you have also extended iterable unpacking. You can do
>>> spam, eggs, *rest = 1, 2, 3, 4
>>> spam
1
>>> eggs
2
>>> rest
[3, 4]
>>> spam, *foo, eggs = 1, 2, 3, 4, 5
>>> spam
1
>>> eggs
5
>>> foo
[2, 3, 4]
>>>
Note that using asterisks makes the respective variable catch-all.
If we have tuple numbers=(1,2,3). We can unpack its values into a, b, and c variables. This is how tuple unpacking can be done:
>>> nums=(1,2,3)
>>> a,b,c=nums
>>> a
1.
>>> b
2.
>>> c