MWZ

MINDWAREZONE

Unpack Tuples

Unpacking a Tuple

Tuple unpacking allows us to extract values from a tuple and assign them to variables in a single line. Unpacking is the process of assigning the tuple items as values to variables.

Example:

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

Output:

Name: Jhon
Age: 20
Studies at: MIT
            

Unpacking a Tuple Using Asterisk*

If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list:  

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)
            

Output:

apple
banana
['cherry', 'strawberry', 'raspberry']
            

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.