Unpack Tuples
Unpacking is the process of assigning the tuple items as values to variables.
Example:
info = ("Marcus", 20, "MIT")
(name, age, university) = info
print("Name:", name)
print("Age:", age)
print("Studies at:", university)
Output:
Name: Marcus
Age: 20
Studies at: MIT
Here, the number of list items is equal to the number of variables.
But what if we have more number of items than the variables?
You can add an *
to one of the variables and depending upon the position of the variable and number of items, Python matches variables to values and assigns them to the variables.
Example 1:
fauna = ("cat", "dog", "horse", "pig", "parrot", "salmon")
(*animals, bird, fish) = fauna
print("Animals:", animals)
print("Bird:", bird)
print("Fish:", fish)
Output:
Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon
Example 2:
fauna = ("parrot", "cat", "dog", "horse", "pig", "salmon")
(bird, *animals, fish) = fauna
print("Animals:", animals)
print("Bird:", bird)
print("Fish:", fish)
Output:
Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon
Example 3:
fauna = ("parrot", "salmon", "cat", "dog", "horse", "pig")
(bird, fish, *animals) = fauna
print("Animals:", animals)
print("Bird:", bird)
print("Fish:", fish)
Output:
Animals: ['cat', 'dog', 'horse', 'pig']
Bird: parrot
Fish: salmon