Packing and unpacking arguments in Python

Welcome back, guys. In this post, we will learn about packing and unpacking the arguments in Python while passing it to the functions.

How to pack and unpack arguments in Python

Let’s dive into one by one.

  • Unpacking arguments
  • Packing arguments

Unpacking arguments

First, we will see how to unpack arguments. Suppose we have a function that takes three arguments. We have a tuple that contains three elements sufficient for function arguments. But, if we pass the whole tuple to the function then see what happens.

def unpack(i,j,k):
    print(i,j,k)
    sum=i+j+k
    print(sum)

tuple=(12,5,67)
unpack(tuple)

Output:

TypeError: unpack() missing 2 required positional arguments: 'j' and 'k'

So, before passing the tuple to the function we have to unpack it. To unpack the tuple we use * and to unpack dictionaries we use ** operator.

Let’s see the example.

def unpack(i,j,k):
    print(i,j,k)
    sum=i+j+k
    print(sum)
tuple=(12,5,67)
unpack(*tuple)

Output:

12 5 67
84

Packing arguments

In the above example, we saw how to unpack arguments. Now we will see how to pack arguments. Before seeing the program we will understand it with an illustration. There is a situation where a function is given but we do not know how many arguments it takes. So we pack the arguments in a tuple.

See the below example.

def pack(*arg,b):
    for i in range (0,len(arg)):
        print(arg[i],b)

tuple1=(12,5,89)
pack(tuple1,b=23)

In the above example, the whole tuple is passed to function with one keyword-only argument. Once the packed tuple is passed to the function it began to work as a normal tuple. We can fetch the argument from tuple using arg[0], arg[1] and so on.

Output:

(12, 5, 89) 23

In this way, packing and unpacking of arguments are done in Python. That’s all for this post. I hope you will understand the method of packing and unpacking the arguments.
If you have any doubts related to this topic please feel free to comment below. We will try our best to help you. If you want the tutorial on any other topic of Python please comment below the topic name explaining the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *