How to unpack a tuple in Python
In this tutorial, we will learn how to unpack a tuple in Python.
In Python, tuples are similar to lists and are declared by parenthesis/round brackets. Tuples are used to store immutable objects. As a result, they cannot be modified or changed throughout the program.
Unpacking a Tuple in Python
While unpacking a tuple, Python maps right-hand side arguments into the left-hand side. In other words, during unpacking, we extract values from the tuple and put them into normal variables.
Let us see an example,
a = ("Harry Potter",15,500) #PACKING (book, no_of_chapters, no_of_pages) = a #UNPACKING print(book) print(no_of_chapters) print(no_of_pages)
Harry Potter 15 500
Also, note that the number of variables on the right as well as the left-hand side should be equal.
If we want to map a group of arguments into a single variable, there is a special syntax available called (*args). This means that there are a number of arguments present in (*args). All values will be assigned in order of specification with the remaining being assigned to (*args).
This can be understood by the following code,
a, *b, c = (10, 20 ,30 ,40 ,50) print(a) print(*b) print(c)
10 20 30 40 50
So, we see that ‘a’ and ‘c’ are assigned the first and last value whereas, *b is assigned with all the in-between values.
Unpacking can also be done with the help of a function. A tuple can be passed in a function and unpacked as a normal variable.
This is made simpler to understand by the following code,
def sum1(a, b): return a + b print(sum1(10, 20)) #normal variables used t = (10, 20) print(sum1(*t)) #Tuple is passed in function
You may also read: