Python - Unpack Tuples
Learn how to unpack tuples in Python, a process where you assign values from a tuple to individual variables. This technique is essential for handling tuples effectively in your code.
Python - Unpack Tuples
Unpacking a Tuple
When creating a tuple, we usually assign values to it, which is known as "packing" a tuple:
Example
fruits = ("apple", "banana", "cherry")
In Python, you can also extract the values back into variables, known as "unpacking" a tuple:
Example
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Output
apple
banana
cherry
Note: The number of variables must match the number of values in the tuple. If not, you must use an asterisk (*) to collect the remaining values as a list.
Using Asterisk (*)
If the number of variables is less than the number of values, you can add an asterisk (*) to a variable name. The remaining values will be assigned to the variable as a list:
Example
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 a variable other than the last, Python will assign values to the variable until the number of remaining values matches the number of remaining variables.
Example
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
Output
apple
['mango', 'papaya', 'pineapple']
cherry