In this section, we will learn what is unpacking and how to unpack a tuple object in Python.
What is Python Unpack Tuples?
The process of assigning the elements of a tuple object as the values of a series of variables in one statement is called unpacking a tuple object.
For example, let’s say we have a tuple object with 3 elements and want to assign those elements as the values of 3 different variables. Using unpacking, we can assign all three elements of the tuple object into three variables in one single statement.
Python Unpacking Tuples Syntax:
(variable1, variable2, variableN) = tupleObject
Note that the number of variables should be equal to the number of elements in the target tuple object. Otherwise we will get an error.
Note: if, however, we have less variable than the number of elements in a tuple, we can use the `*` operator and make one variable to become the container for the remaining elements of the target tuple object.
(variable1, variable2, *variable3) = tupleObject
Here, the first and second elements of the target tupleObject will be assigned to the `variable1` and `variable2` respectively and the rest of elements in the target tuple object will be assigned to the `variable3`. Note that the variable3 becomes a list object in this case!
We can also make a variable other than the last one as the container list for the rest of elements in the target tuple object:
(variable1, variable2, *variable3, variable4) = tupleObject
In this case, the first and second elements of the `tupleObject` will be assigned to the `variable1` and `variable2`, after that the rest of elements will be assigned to the `variable3` until the elements of the `tupleObject` become equal to the number of variables remained in the unpacking. (For this particular example, the last element of the tupleObject will be assigned to the `variable4`).
Example: unpacking tuples in python
tup1 = ("Ellen","Jack", "Omid","Elon", "James","Richard","Jeremy", "Ian", "Kimberly") (var1, var2, var3, *var4) = tup1 print(var1) print(var2) print(var3) print(type(var4)) print(var4)
Ellen Jack Omid <class 'list'> ['Elon', 'James', 'Richard', 'Jeremy', 'Ian', 'Kimberly']