Unpack Tuples

 

Unpack Tuples

Unpacking is the process of assigning the tuple items as values to variables.


Example:

info = ("Maxon", 25, "MIT")
(name, age, university) = info
print("Name:", name)
print("Age:",age)
print("Studies at:",university)

Output:

Name: Maxon
Age: 25
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 then the variables?

You can add an * to one of the variables and depending upon the position of variable and number of items, python matches variables to values and assigns it 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