Unpacking a Tuple in Python
Tuple unpacking is a powerful feature in Python that allows you to assign the values of a tuple to multiple variables in a single line. This technique makes your code more readable and efficient. In other words, It is a process where we extract values from a tuple and assign them to variables in a single step. This feature makes working with tuples more convenient and readable.
Tuple unpacking allows assigning values from a tuple directly to variables:
a, b, c = (100, 200, 300)
print(a)
print(b)
print(c)
Output
100 200 300
Key Rules:
- The number of variables on the left must match the number of elements in the tuple.
- If they do not match, Python raises a
ValueError
.
- Example: a, b = (100, 200, 300) # ValueError: too many values to unpack
Tuple Unpacking Techniques
1. Using _
for Unused Values
If we don’t need certain values, use _
as a throwaway variable or placeholder:
a, _, c = (100, 200, 300)
print(a)
print(c)
Output
100 300
2. Using *
for Variable-Length Unpacking
Python allows catching multiple elements using *, known as the extended unpacking technique:
a, *b = (1, 2, 3, 4, 5)
print(a)
print(b)
Output
1 [2, 3, 4, 5]
3. Unpacking Nested Tuples
Tuples inside tuples can also be unpacked:
nested_tuple = (1, (2, 3), 4)
a, (b, c), d = nested_tuple
print(a)
print(b)
print(c)
print(d)
Output
1 2 3 4
4. Tuple Unpacking with *
in Function Arguments
a. using *args: When defining a function, *args
allows passing multiple arguments as a tuple:
def add(*args):
return sum(args)
print(add(1, 2, 3, 4))
Output
10
b. Using *
for Argument Unpacking: Tuple unpacking can also be used when calling a function:
def add(a, b, c):
return a + b + c
nums = (1, 2, 3)
print(add(*nums))