Unpacking a Tuple
Assigning values to a tuple as you create it is known as "packing" a tuple:
Example
Packing three values into a tuple:
Prompt
Create a tuple called
fruits containing "apple", "banana", and "cherry".
This demonstrates packing a tuple.
Output: complete Python program
main.py
fruits = ("apple", "banana", "cherry")
Example
Unpacking those values into variables:
Prompt
Create a tuple with three fruits and unpack them into variables
green, yellow, and red.
Print each variable.
Output: complete Python program
main.py
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Using Asterisk*
Sometimes you have fewer variables than values. Put an * in front of a variable name and that variable collects the extra values in a list:
Example
The variable "red" collects the remaining values as a list:
Prompt
Create a tuple with five fruits. Unpack the first two into
green and yellow, and the rest into red using an asterisk.
Print all three variables.
Output: complete Python program
main.py
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Example
Here the middle values go into a list called "tropic":
Prompt
Create a tuple with five fruits. Unpack the first into
green, the last into red, and the middle values into tropic using an asterisk.
Print all three variables.
Output: complete Python program
main.py
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)