Python – Unpacking Tuples
Author: Devyra Programming Team
Category: Python Programming Tutorials
Understanding Tuple Packing and Unpacking
In Python, a tuple is an immutable sequence of elements. When we group multiple values together into a tuple and assign them to a single variable, this is known as packing.
fruits = ("apple", "banana", "cherry")
Conversely, we can extract these values from the tuple and assign them to individual variables. This process is known as unpacking.
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Note: The number of variables must match the number of items in the tuple. Otherwise, Python will raise a ValueError
.
Using the Asterisk (*
) in Tuple Unpacking
If you need to unpack only a few values while collecting the rest into a list, Python allows the use of an asterisk (*
) before a variable name.
Example – Collect Remaining Items as a List:
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
The variable red
becomes a list containing the remaining items after the first two values.
Advanced Example – Asterisk in the Middle:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
Here, tropic
receives all middle values, leaving the first and last elements assigned to green
and red
respectively.