Unpack Tuples
What You'll Learn: In this tutorial, you'll discover how to unpack tuples in Python. Unpacking allows you to extract values from a tuple into variables, making it easier to work with the individual elements.
Packing a Tuple
When you create a tuple and assign values to it, this is called "packing" a tuple.
Example Code:
fruits = ("apple", "banana", "cherry")
Unpacking a Tuple
Unpacking a tuple means extracting its values into individual variables.
Example Code:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Output:
apple
banana
cherryWhat's Happening Here?
- The tuple
fruitsis unpacked into the variablesgreen,yellow, andred.
Using Asterisk *
If the number of variables is less than the number of values in the tuple, you can use an asterisk * to assign the remaining values to a list.
Example Code:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
Output:
apple
banana
['cherry', 'strawberry', 'raspberry']What's Happening Here?
- The first two values are assigned to
greenandyellow. - The rest of the values are collected into a list assigned to
red.
Asterisk in Different Positions
If the asterisk is added to a variable other than the last, Python will assign values to that variable until the remaining values fit the remaining variables.
Example Code:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
Output:
apple
['mango', 'papaya', 'pineapple']
cherryWhat's Happening Here?
- The first value is assigned to
green. - The middle values are collected into a list assigned to
tropic. - The last value is assigned to
red.
Try It Yourself: Fun Exercises
- Unpack Your Favorite Colors:
- Create a tuple of your favorite colors.
- Unpack the colors into individual variables.
- Explore with Asterisk:
- Write a tuple with five items.
- Use an asterisk to unpack the first two items into variables and the rest into a list.
Summary:
In this Python tutorial, we learned how to unpack tuples to extract values into variables. We also explored using the asterisk * to handle more values than variables. Unpacking makes it easier to work with individual elements of a tuple. Keep experimenting and have fun with tuples in Python!