• Python Basics

  • Python Variables

  • Operators in Python

  • Conditional Statements in Python

  • Python Lists

  • Python Tuples

  • Python Sets

  • Python Dictionaries

  • Loops in Python

  • Python Arrays and Functions

  • Conclusion

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
1fruits = ("apple", "banana", "cherry")  # Packing a tuple

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

Example: Unpacking a Tuple

python
1fruits = ("apple", "banana", "cherry")
2
3(green, yellow, red) = fruits  # Unpacking the tuple into variables
4
5print(green)   # Output: apple
6print(yellow)  # Output: banana
7print(red)     # Output: cherry

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
1fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
2
3(green, yellow, *red) = fruits  # Using * to gather remaining values into 'red'
4
5print(green)   # Output: apple
6print(yellow)  # Output: banana
7print(red)     # Output: ['cherry', 'strawberry', 'raspberry']

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
1fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
2
3(green, *tropic, red) = fruits  # Using * to gather values into 'tropic'
4
5print(green)    # Output: apple
6print(tropic)   # Output: ['mango', 'papaya', 'pineapple']
7print(red)      # Output: cherry

Frequently Asked Questions