Lessons
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
1
fruits = ("apple", "banana", "cherry") # Packing a tuple
You can then unpack the tuple by assigning its values to variables.
Example: Unpacking a Tuple
python
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
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
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']
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
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