Unpack Tuples
Tuple unpacking allows you to assign tuple values to multiple variables in a single statement.
It is a powerful feature that makes Python code clean, readable, and expressive.
This topic covers basic to advanced tuple unpacking, including edge cases and best practices.
What Is Tuple Unpacking?
Tuple unpacking means extracting values from a tuple and assigning them to variables.
python
data = (10, 20, 30)
a, b, c = data
print(a)
print(b)
print(c)
Each variable receives the value from the corresponding position.
Unpacking Must Match the Number of Items
python
values = (1, 2)
a, b = values
But this causes an error:
python
# a, b, c = values # ValueError
Unpacking with More Readable Variables
python
person = ("Jayesh", 25, "Developer")
name, age, role = person
print(name)
print(age)
print(role)
Unpacking Using Asterisk (*) – Extended Unpacking
Extended unpacking allows you to collect multiple values into a list.
python
numbers = (1, 2, 3, 4, 5)
a, *b = numbers
print(a)
print(b)
Unpack Middle Values
python
numbers = (1, 2, 3, 4, 5)
a, *b, c = numbers
print(a)
print(b)
print(c)
Ignore Unwanted Values
python
data = (10, 20, 30, 40)
a, _, _, d = data
print(a)
print(d)
Unpacking Nested Tuples
python
data = ((1, 2), (3, 4))
(a, b), (c, d) = data
print(a, b)
print(c, d)
Unpacking in Loops
Tuple unpacking is commonly used in loops.
python
pairs = [(1, 2), (3, 4), (5, 6)]
for x, y in pairs:
print(x, y)
Unpacking with Functions
Functions often return tuples.
python
def calculate(a, b):
return a + b, a - b
result = calculate(10, 5)
print(result)
python
sum_val, diff_val = calculate(10, 5)
print(sum_val)
print(diff_val)
Swap Values Using Tuple Unpacking
One of Python’s most elegant features.
python
a = 10
b = 20
a, b = b, a
print(a)
print(b)
Unpacking with enumerate()
python
fruits = ("apple", "banana", "cherry")
for index, value in enumerate(fruits):
print(index, value)
Common Mistakes
Incorrect Number of Variables
python
values = (1, 2, 3)
# a, b = values # ValueError
Expecting * to Create a Tuple
python
numbers = (1, 2, 3, 4)
a, *b = numbers
print(type(b))
b is a list.Best Practices
- Use meaningful variable names
- Use
_for ignored values - Prefer unpacking for readability
- Use extended unpacking when needed
Summary
- Tuple unpacking assigns values in one step
- Number of variables must match items
*allows flexible unpacking- Works with loops and functions
- Ideal for swapping values and clean code
- Improves readability and efficiency