What is pack and unpack in python?

We use two operators * [for tuples] and ** [for dictionaries].
 

Background 
Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the function, the call doesn’t work. 
 

Python3

def fun[a, b, c, d]:

    print[a, b, c, d]

my_list = [1, 2, 3, 4]

fun[my_list]

Output : 

TypeError: fun[] takes exactly 4 arguments [1 given]

  
Unpacking 
We can use * to unpack the list so that all elements of it can be passed as different parameters.
 

Python3

def fun[a, b, c, d]:

    print[a, b, c, d]

my_list = [1, 2, 3, 4]

fun[*my_list]

Output : 

[1, 2, 3, 4]

We need to keep in mind that the no. of arguments must be the same as the length of the list that we are unpacking for the arguments.

Python3

args = [0, 1, 4, 9]

def func[a, b, c]:

    return a + b + c

func[*args]

Output:

Traceback [most recent call last]:
  File "/home/592a8d2a568a0c12061950aa99d6dec3.py", line 10, in 
    func[*args]
TypeError: func[] takes 3 positional arguments but 4 were given

As another example, consider the built-in range[] function that expects separate start and stops arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: 

Python3

>>>

>>> range[3, 6

[3, 4, 5]

>>> args = [3, 6]

>>> range[*args] 

[3, 4, 5]

Packing 
When we don’t know how many arguments need to be passed to a python function, we can use Packing to pack all arguments in a tuple. 
 

Python3

def mySum[*args]:

    return sum[args]

print[mySum[1, 2, 3, 4, 5]]

print[mySum[10, 20]]

Output: 
 

15
30

The above function mySum[] does ‘packing’ to pack all the arguments that this method call receives into one single variable. Once we have this ‘packed’ variable, we can do things with it that we would with a normal tuple. args[0] and args[1] would give you the first and second argument, respectively. Since our tuples are immutable, you can convert the args tuple to a list so you can also modify, delete, and re-arrange items in i.
 

Packing and Unpacking 
Below is an example that shows both packing and unpacking. 
 

Python3

def fun1[a, b, c]:

    print[a, b, c]

def fun2[*args]:

    args = list[args]

    args[0] = 'Geeksforgeeks'

    args[1] = 'awesome'

    fun1[*args]

fun2['Hello', 'beautiful', 'world!']

Output: 
 

[Geeksforgeeks, awesome, world!]

** is used for dictionaries 
 

Python3

def fun[a, b, c]:

    print[a, b, c]

d = {'a':2, 'b':4, 'c':10}

fun[**d]

Output:
 

2 4 10

Here ** unpacked the dictionary used with it, and passed the items in the dictionary as keyword arguments to the function. So writing “fun[1, **d]” was equivalent to writing “fun[1, b=4, c=10]”.
 

Python3

def fun[**kwargs]:

    print[type[kwargs]]

    for key in kwargs:

        print["%s = %s" % [key, kwargs[key]]]

fun[name="geeks", ID="101", language="Python"]

Output

name = geeks
ID = 101
language = Python

Applications and Important Points 

  1. Used in socket programming to send a vast number of requests to a server.
  2. Used in the Django framework to send variable arguments to view functions.
  3. There are wrapper functions that require us to pass in variable arguments.
  4. Modification of arguments becomes easy, but at the same time validation is not proper, so they must be used with care.

Reference : 
//hangar.runway7.net/python/packing-unpacking-arguments
This article is contributed by Shwetanshu Rohatgi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 


What is packing and unpacking?

The pack function takes a list of values to be packed as a second argument and returns a scalar character string containing the packed values. The unpack function takes a character string containing the values to be unpacked as a second argument, and returns a list of individual values extracted from the string.

What is packing in Python?

Practical Data Science using Python Above operation is called 'packing” as it pack all the arguments into one single variable that this method call receives into a tuple called args. We can use name other than args, but args is the most common and pythonic way of doing things.

What is packing and unpacking in tuples?

In another way, it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

What is unpack operator in Python?

Both * and ** are the operators that perform packing and unpacking in Python. The * operator [quite often associated with args] can be used with any iterable [such as a tuple, list and strings], whereas the ** operator, [quite often associated with kwargs] can only be used on dictionaries.

Chủ Đề