p

python tutorial - Python Unpack | Packing and Unpacking Arguments in Python - learn python - python programming



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 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 list to the function, the call doesn’t work.

python - Sample - python code :

# A Python program to demonstrate need 
# of packing and unpacking
 
# A sample function that takes 4 arguments
# and prints them.
def fun(a, b, c, d):
    print(a, b, c, d)
 
# Driver Code
my_list = [1, 2, 3, 4]
 
# This doesn't work
fun(my_list)
click below button to copy the code. By Python tutorial team

python tutorial - Output :

TypeError: fun() takes exactly 4 arguments (1 given)
Unpacking

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

python - Sample - python code :

# A sample function that takes 4 arguments
# and prints the,
def fun(a, b, c, d):
    print(a, b, c, d)
 
# Driver Code
my_list = [1, 2, 3, 4]
 
# Unpacking list into four arguments
fun(*my_list)
click below button to copy the code. By Python tutorial team

python tutorial - Output :

(1, 2, 3, 4)

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

python - Sample - python code :

>>>
>>> range(3, 6)  # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)  # call with arguments unpacked from a list
[3, 4, 5]
click below button to copy the code. By Python tutorial team

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.

python - Sample - python code :

# A Python program to demonstrate use
# of packing
 
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
    sum = 0
    for i in range(0, len(args)):
        sum = sum + args[i]
    return sum
 
# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))
click below button to copy the code. By Python tutorial team

python tutorial - 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 so if you convert the args tuple to a list you can also modify, delete and re-arrange items in i just like a normal list.

Packing and Unpacking


Below is an example that shows both packing and unpacking.

python - Sample - python code :

# A Python program to demonstrate both packing and
# unpacking.
 
# A sample python function that takes three arguments
# and prints them
def fun1(a, b, c):
    print(a, b, c)
 
# Another sample function.
# This is an example of PACKING. All arguments passed
# to fun2 are packed into tuple *args.
def fun2(*args):
 
    # Convert args tuple to a list so we can modify it
    args = list(args)
 
    # Modifying args
    args[0] = 'Wikitechy'
    args[1] = 'awesome'
 
    # UNPACKING args and calling fun1()
    fun1(*args)
 
# Driver code
fun2('Hello', 'beautiful', 'world!')
click below button to copy the code. By Python tutorial team

python tutorial - Output :

(Wikitechy, awesome, world!)

** is used for dictionaries

python - Sample - python code :

# A sample program to demonstrate unpacking of
# dictionary items using **
def fun(a, b, c):
    print(a, b, c)
 
# A call with unpacking of dictionary
d = {'a':2, 'b':4, 'c':10}
fun(**d)
click below button to copy the code. By Python tutorial team

python tutorial - 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=8, c=16)”.

python - Sample - python code :

# A Python program to demonstrate packing of
# dictionary items using **
def fun(**kwargs):
 
    # kwargs is a dict
    print(type(kwargs))
 
    # Printing dictionary items
    for key in kwargs:
        print("%s = %s" % (key, kwargs[key]))
 
# Driver code
fun(name="wiki", ID="101", language="Python")
click below button to copy the code. By Python tutorial team

python tutorial - Output :

<class 'dict'>
language = Python
name = wiki
ID = 101

Applications and Important Points
1. Used in socket programming to send a infinite no. of requests to server.
2. Used in Django framework to send variable arguments to view functions.
3. There are wrapper functions that require us to pass in variable argurents.
4. Modification of arguments become easy but at the same time validation is not proper so they must be used with care.


Wikitechy tutorial site provides you all the learn python , learn python for dummies , python coding classes , python online training course , online python course , python training courses , python programming classes , python classes online , python programming for dummies , online python class

Related Searches to Packing and Unpacking Arguments in Python