In Python, we can unpack a tuple with a variable length using star expressions (also known as extended unpacking). In the absence of matching under of values, a program can cause a “too many values to unpack” exception.
1. Unpack a Tuple with Variable Length
Star expressions, introduced in Python 3, allow us to assign parts of a tuple to variables while handling the remaining elements as a single entity. We can use the
* operator to achieve this.
# Example tuple with a variable length my_tuple = (1, 2, 3, 4, 5) # Unpack the first two elements and collect the rest in another variable first, second, *rest = my_tuple # Print the results print("First:", first) print("Second:", second) print("Rest:", rest)
Notice the program output. The
rest variable holds the remaining elements as a list.
First: 1 Second: 2 Rest: [3, 4, 5]
Note that we can use the star expression at various positions in variable assignments to collect elements dynamically. We can use them at the beginning, middle, or end of variable assignments as well.
# Example tuple with a variable length my_tuple = (1, 2, 3, 4, 5) # Collect the first two elements, skip the third, and collect the rest first, second, *skip, last = my_tuple # Print the results print("First:", first) print("Second:", second) print("Last:", last) print("Skipped:", skip)
The program output:
First: 1 Second: 2 Last: 5 Skipped: [3, 4]
2. Unpack Tuple and Ignore Unwanted Values
Sometimes, we might want to unpack values and throw some of them away. In Python, we can unpack a tuple and ignore unwanted values by using the underscore (
_) as a placeholder for those values.
This is extremely helpful when we are only interested in extracting specific elements from a tuple and don’t need to use or assign names to the unused elements to keep the code clean.
The underscore is a convention in Python to indicate that a variable is not going to be used, making the code more readable and self-explanatory.
# Example tuple with unwanted values my_tuple = (1, 2, 3, 4, 5) # Unpack the tuple and ignore unwanted values first, _, third, _, _ = my_tuple # Print the values you're interested in print("First:", first) print("Third:", third)
3. Error: too many values to unpack
While unpacking a tuple, this error occurs when the number of variables on the left side of the assignment doesn’t match the number of elements in the tuple or iterable on the right side, and we are not using the star expression also.
my_tuple = (1, 2, 3, 4, 5) first, second, third = my_tuple ...
In the above example, we have a tuple
my_tuple with five elements, but we’re trying to unpack three values into
third. This will result in the “too many values to unpack” error because there is a mismatch between the number of elements in the tuple and the number of variables to unpack.
ERROR! Traceback (most recent call last): File "<string>", line 3, in <module> ValueError: too many values to unpack (expected 3)
Happy Learning !!