Loading...

Unpack Tuples in Python

Unpack Tuples in Python

In Python, tuples are ordered collections of items that can be packed into a single variable. However, you can also extract these values back into individual variables, a process known as "unpacking." This lesson will explain how to unpack tuples, including how to handle cases where the number of variables does not match the number of values.

1. Unpacking a Tuple

When you create a tuple, you typically assign values to it. This process is referred to as packing a tuple.

Example: Packing a Tuple

python
1 lines
|
15/ 500 tokens
1
fruits = ("apple", "banana", "cherry")  # Packing a tuple
Code Tools

You can then unpack the tuple by assigning its values to variables.

Example: Unpacking a Tuple

python
7 lines
|
51/ 500 tokens
1
2
3
4
5
6
7
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits  # Unpacking the tuple into variables

print(green)   # Output: apple
print(yellow)  # Output: banana
print(red)     # Output: cherry
Code Tools

Note: The number of variables must match the number of values in the tuple. If they do not match, you can use an asterisk (*) to collect the remaining values as a list.

2. Using Asterisk (

If the number of variables is less than the number of values in the tuple, you can use an asterisk before a variable name to collect the excess values into a list.

Example: Assign the Rest of the Values as a List

python
7 lines
|
69/ 500 tokens
1
2
3
4
5
6
7
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits  # Using * to gather remaining values into 'red'

print(green)   # Output: apple
print(yellow)  # Output: banana
print(red)     # Output: ['cherry', 'strawberry', 'raspberry']
Code Tools

3. Asterisk in Different Positions

If the asterisk is placed before a variable name that is not the last variable, Python will assign values to that variable until the remaining values match the number of variables left.

Example: Unpacking with Asterisk in the Middle

python
7 lines
|
65/ 500 tokens
1
2
3
4
5
6
7
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits  # Using * to gather values into 'tropic'

print(green)    # Output: apple
print(tropic)   # Output: ['mango', 'papaya', 'pineapple']
print(red)      # Output: cherry
Code Tools