Python Tuple Unpacking


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

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.

In [1]:
names = ("Bill", "Steve")
first, second = names

print(first)
print(second)

Tuple with four variables.

In [2]:
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

In [1]:
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.

In [1]:
names = ("Bill", "Steve", "Tim", "Sam", "Oliver")
firstname, secondname, *others = names

print(firstname)
print(secondname)
print(others)
Bill
Steve
['Tim', 'Sam', 'Oliver']

Getting first and last name.

In [2]:
names = ("Bill", "Steve", "Tim", "Sam", "Oliver")
firstname, *others, lastname = names

print(firstname)
print(lastname)
print(others)
Bill
Oliver
['Steve', 'Tim', 'Sam']

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.

In [1]:
names1 = ("Bill", "Steve")
names2 = ("Tim", "Sam")

final = (*names1, *names2)
print(final)
('Bill', 'Steve', 'Tim', 'Sam')

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.

In [1]:
a = 5
b = 10

a, b = b, a

print(a, b)
10 5

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.

In [1]:
names = ("Bill", "Steve")
print(names)
('Bill', 'Steve')

Tuple without parenthesis .

In [2]:
names = "Bill", "Steve"
print(names)
('Bill', 'Steve')

5 Different uses of Tuple Unpacking

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.

In [1]:
names_tuple = ("Bill", "Steve", "Tim", "Sam", "Oliver")
names_list = [*names_tuple]

print(names_list)
['Bill', 'Steve', 'Tim', 'Sam', 'Oliver']

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.

In [1]:
def print_details(name, gender, age):
    print("Name:", name)
    print("Gender:", gender)
    print("Age:", age)


employee_details = ("Elon", "Male", "57")
print_details(*employee_details)
Name: Elon
Gender: Male
Age: 57

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.

In [1]:
my_tuple = ((1, 2), (3, 4), (5, 6))
result = [x * y for x, y in my_tuple]
print(result)
[2, 12, 30]

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.

In [1]:
employee_details = ("Elon", "Male", "57")

my_dictionary = dict(zip(('name', 'gender', 'age'), employee_details))

print(my_dictionary)
{'name': 'Elon', 'gender': 'Male', 'age': '57'}

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.

In [1]:
my_tuple = (3, 4)

result = (lambda x,y: x * y)(*my_tuple)

print(result)
12

References

  1. Python Unpacking Tuple
  2. Unpack a tuple and list in Python