Open In App

Packing and Unpacking Arguments in Python

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 
 

Python
# 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.
 

Python
# 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.

Python
# 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: 

Python
>>>
>>> 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. 
 

Python
# 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. 
 

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

Python
 
# 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, i.e writing “fun(1, **d)” was equivalent to writing “fun(1, b=4, c=10)”.
 

Python
# 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 | 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
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
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. Examp
3 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Python: Passing Dictionary as Arguments to Function
A dictionary in Python is a collection of data which is unordered and mutable. Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value. Refer to the belo
2 min read
Tuple as function arguments in Python
Tuples have many applications in all the domains of Python programming. They are immutable and hence are important containers to ensure read-only access, or keeping elements persistent for more time. Usually, they can be used to pass to functions and can have different kinds of behavior. Different cases can arise. Case 1: fnc(a, b) - Sends a and b
2 min read
Python - pass multiple arguments to map function
The map() function is a built-in function in Python, which applies a given function to each item of iterable (like list, tuple etc.) and returns a list of results or map object. Syntax : map( function, iterable ) Parameters : function: The function which is going to execute for each iterableiterable: A sequence or collection of iterable objects whi
3 min read
Executing functions with multiple arguments at a terminal in Python
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li&gt; Using argparse module The Python sys module allows access to command-line argument
4 min read
How to handle invalid arguments with argparse in Python?
Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arguments are passed. It even allows customizing the
4 min read
Pass Arguments to the Metaclass from the Class in Python
Metaclasses in Python provide a powerful way to control the creation and behavior of classes. They act as the "class of a class" and allow you to customize class creation and behavior at a higher level. One interesting aspect of metaclasses is the ability to pass arguments from a class to its metaclass during the class definition. What is a Metacla
3 min read
Command Line Arguments in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are:  Using sys.argvUsing getopt moduleUsing argparse moduleUsing sys.argvThe sys module provides functions and
5 min read
Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is
7 min read
How to Print Multiple Arguments in Python?
An argument is a value that is passed within a function when it is called.They are independent items, or variables, that contain data or codes. During the time of call each argument is always assigned to the parameter in the function definition. Example: Simple argument [GFGTABS] Python def GFG(name, num): print(&quot;Hello from &quot;, name +
3 min read
How to find the number of arguments in a Python function?
In this article, we are going to see how to count the number of arguments of a function in Python. We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of ar
3 min read
How to bind arguments to given values in Python functions?
In Python, binding arguments to specific values can be a powerful tool, allowing you to set default values for function parameters, create specialized versions of functions, or partially apply a function to a set of arguments. This technique is commonly known as "partial function application" and can be achieved using Python's functools.partial as
3 min read
Core arguments in serializer fields - Django REST Framework
Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. This article revolves around various arguments that serializer
6 min read
Functions that accept variable length key value pair as arguments
To pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments in their function. Syntax: def functionName(**anything): statement(s) Note: adding '**' to any term makes it a kwargs
2 min read
How to Pass Arguments to Tkinter Button Command?
When a user hits the button on the Tkinter Button widget, the command option is activated. In some situations, it's necessary to supply parameters to the connected command function. In this case, the procedures for both approaches are identical; the only thing that has to vary is the order in which you use them. Method 1: Pass Arguments to Tkinter
2 min read
How to pass arguments to shell script in crontab ?
In this article, we will discuss how to schedule shell scripts in crontab and to pass necessary parameters as well. First, let's create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run. #! /
2 min read
Passing URL Arguments in Flask
In this article, we will cover how to Pass URL Arguments in Flask using Python. URL converters in Flask are mentioned in angular brackets (&lt;&gt;). These unique converters are designed to let us generate extremely dynamic URLs, where a part of the URL is regarded as a variable. For that we have created three different endpoints to understand thre
4 min read
How to pass multiple arguments to function ?
A Routine is a named group of instructions performing some tasks. A routine can always be invoked as well as called multiple times as required in a given program.  When the routine stops, the execution immediately returns to the stage from which the routine was called. Such routines may be predefined in the programming language or designed or imple
5 min read
Get the number of Explicit Arguments in the Init of a Class
In Python, the __init__ method is used for initializing a newly created object. It typically contains parameters that set the initial state of an object. To count the number of explicit arguments in the __init__ method of a class, we can use the inspect module from Python's standard library. In this article, we will see how we can get the number of
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Creating and updating PowerPoint Presentations in Python using python - pptx
python-pptx is library used to create/edit a PowerPoint (.pptx) files. This won't work on MS office 2003 and previous versions. We can add shapes, paragraphs, texts and slides and much more thing using this library. Installation: Open the command prompt on your system and write given below command: pip install python-pptx Let's see some of its usag
4 min read
Learn DSA with Python | Python Data Structures and Algorithms
This tutorial is a beginner-friendly guide for learning data structures and algorithms using Python. In this article, we will discuss the in-built data structures such as lists, tuples, dictionaries, etc, and some user-defined data structures such as linked lists, trees, graphs, etc, and traversal as well as searching and sorting algorithms with th
15+ min read
Setting up ROS with Python 3 and Python OpenCV
Setting up a Robot Operating System (ROS) with Python 3 and OpenCV can be a powerful combination for robotics development, enabling you to leverage ROS's robotics middleware with the flexibility and ease of Python programming language along with the computer vision capabilities provided by OpenCV. Here's a step-by-step guide to help you set up ROS
3 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Practice Tags :