Introduction to Tuple Unpacking
In Python, tuple has powerful features, using which we can assign all the values of the tuples to the left-hand side variables in a single statement. This is known as tuple unpacking. When we assign values to the tuple, this is known as tuple packing and when we extract values from the tuple, this is known as tuple unpacking. This process is not limited to tuples, it works with lists as well.
Tuple Unpacking
The process of assigning tuple items to the variables is known as tuple unpacking. We assign items of the tuple to the equivalent comma separated variables. Make sure, the number of variables on the left-hand side matches with the number of items in the tuple.
In the below example, we have a names tuples with two names. To unpack that tuple, we need to use the two variables. In the same way, if we have a tuple with four items, we need four variables to unpack them.
Tuple with two variables.
names = ("Bill", "Steve")
first, second = names
print(first)
print(second)
Tuple with four variables.
names = ("Bill", "Steve", "Elon", "Jeff")
first, second, third, fourth = names
print(first)
print(second)
print(third)
print(fourth)
ValueError
Python throws the ValueError when the number of items in the tuple does not match with the number of variables. In the below example, we are trying to unpack a “names” tuple with the 4 names in 3 variables. Python throws ValueError in this case, saying too many values to unpack.
ValueError
names = ("Bill", "Steve", "Elon", "Jeff")
first, second, third = names
print(first)
print(second)
print(third)
Asterisk* Approach
We can assign multiple values to a single variable. This will work in case we have more number of items than variables. For this, we prepend the asterisk * with the variable that will hold multiple items. Note: Asterisk cannot be used with multiple variables in a single statement, it can be used with a single variable only.
This approach is useful when we don’t want to unpack all the values of the tuple. In the below example, we want to unpack only two names. For the remaining three names, a variable with the asterisk is used. Observe, in the output variable “others” hold the list of names.
Getting first and second name.
names = ("Bill", "Steve", "Tim", "Sam", "Oliver")
firstname, secondname, *others = names
print(firstname)
print(secondname)
print(others)
Getting first and last name.
names = ("Bill", "Steve", "Tim", "Sam", "Oliver")
firstname, *others, lastname = names
print(firstname)
print(lastname)
print(others)
Asterisk* to Merge Tuples
An asterisk can be used on the right-hand side, to unpack two tuples and merge them into a single. For example, here an asterisk is used with the names1 and names2 tuples and merged them into the final tuple.
names1 = ("Bill", "Steve")
names2 = ("Tim", "Sam")
final = (*names1, *names2)
print(final)
Example: Swap two variables without using the third one.
Tuple unpacking allows us to swap two variables in a single line without using the third one and without using any temporary variables.
a = 5
b = 10
a, b = b, a
print(a, b)
Tuple Packing
The process of assigning multiple items to a tuple is known as tuple packing. Parenthesis are not mandatory to create a tuple. Tuple can also be created without parenthesis.
Tuple packing.
names = ("Bill", "Steve")
print(names)
Tuple without parenthesis .
names = "Bill", "Steve"
print(names)
5 Different uses of Tuple Unpacking
1. Type Casting
This approach can be used to type cast tuple to list. All the elements of the tuple will be extracted using the Asterisk, enclose in the square brackets and each element will be separated by a comma.
names_tuple = ("Bill", "Steve", "Tim", "Sam", "Oliver")
names_list = [*names_tuple]
print(names_list)
2. Unpack as Argument
Elements of the tuple can be passed as an argument to the function using the Asterisk. It will unpack the tuple and pass multiple arguments to the tuple. Here, we need not specify each argument manually.
def print_details(name, gender, age):
print("Name:", name)
print("Gender:", gender)
print("Age:", age)
employee_details = ("Elon", "Male", "57")
print_details(*employee_details)
3. Unpack using List Comprehension
List comprehension is a perfect approach to unpack nested tuples. Once each variable is extracted, we can perform any operation with them. For example, in the below code, we are multiplying the elements of the tuple.
my_tuple = ((1, 2), (3, 4), (5, 6))
result = [x * y for x, y in my_tuple]
print(result)
4. Unpack as a Dictionary
Tuple can also be unpacked as the dictionary using the zip function. The zip function is used to create the key-value pair. Both the keys and values will be supplied to the zip function as the tuples.
employee_details = ("Elon", "Male", "57")
my_dictionary = dict(zip(('name', 'gender', 'age'), employee_details))
print(my_dictionary)
5. Unpack using Lambda Functions
Tuple can be unpacked using the asterisk and the lambda. After extracting the elements of the tuple, we can perform any operation on them.
my_tuple = (3, 4)
result = (lambda x,y: x * y)(*my_tuple)
print(result)