Open In App

Packing and Unpacking Arguments in Python

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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)


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




# 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)


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




# Error when len(args) != no of actual arguments
# required by the function
 
args = [0, 1, 4, 9]
 
 
def func(a, b, c):
    return a + b + c
 
 
# calling function with unpacking args
func(*args)


Output:

Traceback (most recent call last):
  File "/home/592a8d2a568a0c12061950aa99d6dec3.py", line 10, in <module>
    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# normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)  # call with arguments unpacked from a list
[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




# A Python program to demonstrate use
# of packing
 
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
    return sum(args)
 
# Driver code
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




# 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] = 'Geeksforgeeks'
    args[1] = 'awesome'
 
    # UNPACKING args and calling fun1()
    fun1(*args)
 
# Driver code
fun2('Hello', 'beautiful', 'world!')


Output: 
 

(Geeksforgeeks, awesome, world!)

The time complexity of the given Python program is O(1), which means it does not depend on the size of the input.

The auxiliary space complexity of the program is O(n), where n is the number of arguments passed to the fun2 function.

** is used for dictionaries 
 

Python3




# 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)


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




# 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="geeks", ID="101", language="Python")


Output

<class 'dict'>
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 : 
http://hangar.runway7.net/python/packing-unpacking-arguments

 



Previous Article
Next Article

Similar Reads

Unpacking arguments in Python
If you have used Python even for a few days now, you probably know about unpacking tuples. Well for starter, you can unpack tuples or lists to separate variables but that not it. There is a lot more to unpack in Python. Unpacking without storing the values: You might encounter a situation where you might not need all the values from a tuple but you
3 min read
Unpacking a Tuple in Python
Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of value
3 min read
Python | Unpacking tuple of lists
Given a tuple of lists, write a Python program to unpack the elements of the lists that are packed inside the given tuple. Examples: Input : (['a', 'apple'], ['b', 'ball']) Output : ['a', 'apple', 'b', 'ball'] Input : ([1, 'sam', 75], [2, 'bob', 39], [3, 'Kate', 87]) Output : [1, 'sam', 75, 2, 'bob', 39, 3, 'Kate', 87] Approach #1 : Using reduce()
3 min read
Python | Unpacking dictionary keys into tuple
In certain cases, we might come into a problem in which we require to unpack dictionary keys to tuples. This kind of problem can occur in cases we are just concerned about the keys of dictionaries and wish to have a tuple of them. Let's discuss certain ways in which this task can be performed in Python. Example Input: {'Welcome': 1, 'to': 2, 'GFG':
4 min read
Python | Unpacking nested tuples
Sometimes, while working with Python list of tuples, we can have a problem in which we require to unpack the packed tuples. This can have a possible application in web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension This task can be performed using list comprehension in which we iter
6 min read
Python - Unpacking Values in Strings
Given a dictionary, unpack its values into a string. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "Gfg", 9 : "Best"} Output : First value is Gfg Second is Best Explanation : After substitution, we get Gfg and Best as values. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "G", 9 : "f"} Output : First v
3 min read
How to Run Another Python script with Arguments in Python
Running a Python script from another script and passing arguments allows you to modularize code and enhance reusability. This process involves using a subprocess or os module to execute the external script, and passing arguments can be achieved by appending them to the command line. In this article, we will explore different approaches to Running a
3 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
2 min read
Deep dive into Parameters and Arguments in Python
There is always a little confusion among budding developers between a parameter and an argument, this article focuses to clarify the difference between them and help you to use them effectively. Parameters: A parameter is the variable defined within the parentheses during function definition. Simply they are written when we declare a function. Exam
2 min read
Pass function and arguments from node.js to Python
Prerequisites: How to run python scripts in node.js using the child_process module. In this article, we are going to learn how to pass functions and arguments from node.js to Python using child_process. Although Node.js is one of the most widely used web development frameworks, it lacks machine learning, deep learning, and artificial intelligence l
4 min read
Practice Tags :