Python offers immutable data types known as tuples. In this article, we will learn about packing an unpacking tuple type in Python 3.x. Or earlier.
Packing and Unpacking a Tuple
Python offers a very powerful tuple assignment tool that maps right hand side arguments into left hand side arguments. THis act of mapping together is known as unpacking of a tuple of values into a norml variable. WHereas in packing, we put values into a regular tuple by means of regular assignment.
Now let’s take a look at its implementation −
Example
# Packing tuple varibles under one varible name tup = ("Tutorialspoint", "Python", "Unpacking a tuple") # Packing tuple varibles into a group of arguments (website, language, topic) = tup # print college name print(website,"\t",language," ",topic)
Output
Tutorialspoint Python Unpacking a tuple
During the unpacking of tuple, the total number of variables on the left-hand side should be equivalent to the total number of values in given tuple tup.
Python gives the syntax to pass optional arguments (*arguments) for tuple unpacking of arbitrary length. All values will be assigned to every variable in the order of their specification and all remaining values will be assigned to *arguments . Let’s consider the following code.
Example
# Packing tuple variables under one variable name tup = ("Tutorialspoint", "Python","3.x.",":Data Structure","Unpacking a tuple") # Packing tuple variables into a group of arguments (website,*language, topic) = tup # print college name print(website,"\t",*language," ",topic)
Output
Tutorialspoint Python 3.x. :Data Structure Unpacking a tuple
In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments.
“*_” is used to specify the arbitrary number of arguments in the tuple.
Example
# Packing tuple varibles under one varible name tup = ("Tutorialspoint", "Python","3.x.","Data Structure:","Unpacking a tuple") # UnPacking tuple variables into a group of arguments and skipping unwanted arguments (website,*_,typ,topic) = tup # print college name print(website,"\t",typ," ",topic)
Output
Tutorialspoint Data Structure: Unpacking a tuple
In case we want to skip only one argument then we can replace “*_” by “_”
Conclusion
In this article, we learnt how we can pack and unpack tuples in a variety of Ways.