Packing and Unpacking Arguments in Python

Packing and Unpacking Arguments in Python

4 mins read956 Views Comment
Updated on Mar 16, 2023 17:19 IST

When talking about functions in Python, the terms “arguments” and “keyword arguments” are introduced. During the function definition, we frequently encounter *args and **kwargs being passed as arguments.

2023_02_Understanding-Break-Statement-in-C-12.jpg

Today, we will learn how arguments in Python are packed and unpacked. We will be covering the following sections:

Types of Function Arguments in Python

There are two types of function arguments in Python:

  • Positional Arguments: These are the traditional arguments that are passed to a function in a specific order, based on their position in the function definition. Positional arguments are usually used when the order of the arguments is important.
    • Keyword Arguments: These are arguments that are passed to a function using the name of the argument and its value. The order of the arguments doesn’t matter in this case. Keyword arguments are often used to make the code more readable and to specify default values for arguments that may not always be provided.

Additionally, there are two special syntaxes in Python that allow a function to receive a variable number of arguments:

  • *args (or “variable-length positional arguments”): This syntax allows a function to receive any number of positional arguments. The arguments are passed to the function as a tuple.
  • **kwargs (or “variable-length keyword arguments”): This syntax allows a function to receive any number of keyword arguments. The arguments are passed to the function as a dictionary.

Explore free Python courses

What are Packing Arguments?

When you think of “packing arguments,” you’re thinking about bundling arguments together into a single variable, which in this case is a tuple containing all the arguments. This makes it possible to access each argument individually, similar to accessing values in a tuple, for example, tuple[0], tuple[1], etc. Additionally, it allows us to convert the tuple into a list, which can then be manipulated.

Examples

Here’s an example that demonstrates how to use the * operator to “pack” arguments into a single tuple in Python:

 
def pack_args(*args):
print(type(args))
for arg in args:
print(arg)
#Call the function with multiple arguments
pack_args(1, 2, 3, "Hello", [1, 2, 3])
Copy code

Output:

 
<class 'tuple'="">
1
2
3
Hello
[1, 2, 3]
Copy code

In this example, the pack_args function takes a variable number of arguments using the * operator. This operator allows the function to accept any number of arguments, which are then packed into a single tuple named args. The type of args is tuple, and the elements can be accessed individually, as demonstrated by the for-loop.

Here’s another example that demonstrates how to use the ** operator to “pack” keyword arguments into a single dictionary in Python:

 
def pack_kwargs(**kwargs):
print(type(kwargs))
for key, value in kwargs.items():
print(f"{key}: {value}")
#Call the function with multiple keyword arguments
pack_kwargs(name="John", age=30, country="USA")
Copy code

Output:

 
<class 'dict'="">
name: John
age: 30
country: USA
Copy code

In this example, the pack_kwargs function takes a variable number of keyword arguments using the ** operator. This operator allows the function to accept any number of keyword arguments, which are then packed into a single dictionary named kwargs. The type of kwargs is dict, and the key-value pairs can be accessed using a for-loop, as demonstrated in the code.

What are Unpacking Arguments?

Unpacking arguments in Python refers to the process of taking a packed tuple or dictionary and “unpacking” its elements into separate variables. The * and ** operators can be used to unpack the arguments, respectively.

Examples

Here’s an example that demonstrates how to unpack a tuple of positional arguments using the * operator:

 
def add(a, b, c):
print(a + b + c)
#Call the function with a packed tuple of arguments
args = (1, 2, 3)
add(*args)
Copy code

Output:

 
6
Copy code

In this example, the add function takes three positional arguments, a, b, and c. We create a tuple named args that contains the values we want to pass to the function. To unpack the values from the tuple, we use the * operator in front of args in the function call. This unpacks the values from the tuple and passes them as separate positional arguments to the function.

Here’s another example that demonstrates how to unpack a dictionary of keyword arguments using the ** operator:

 
def print_person(name, age, country):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Country: {country}")
#Call the function with a packed dictionary of keyword arguments
person = {"name": "John", "age": 30, "country": "USA"}
print_person(**person)
Copy code

Output:

 
Name: John
Age: 30
Country: USA
Copy code

In this example, the print_person function takes three keyword arguments, name, age, and country. We create a dictionary named person that contains the values we want to pass to the function. To unpack the values from the dictionary, we use the ** operator in front of person in the function call. This unpacks the values from the dictionary and passes them as separate keyword arguments to the function.

Working of Packing and Unpacking Arguments Together

It’s possible to use both packing and unpacking arguments simultaneously in a single function call. Here’s an example:

 
def add_subtract(a, b, c, *args, **kwargs):
result = a + b - c
for arg in args:
result += arg
for key, value in kwargs.items():
result += value
return result
numbers = (1, 2, 3)
more_numbers = (4, 5, 6)
additional_numbers = {"x": 7, "y": 8, "z": 9}
Copy code

Output:

 
39
Copy code

In the above example, the add_subtract function takes three positional arguments, a, b, and c, followed by *args for packing any additional positional arguments and **kwargs for packing any additional keyword arguments.

We create two tuples numbers and more_numbers and a dictionary additional_numbers that contain the values we want to pass to the function. To unpack the values from the tuples and dictionary, we use the * operator for the tuples and the ** operator for the dictionary in the function call. This unpacks the values from the tuples and dictionary and passes them as separate positional and keyword arguments to the function.

How to Use Python Print Function
How to Use Python Print Function
Python print function is used to display the output on the screen. In this article, we will learn how to use python print function using different examples.
How to Use Python zip Function
How to Use Python zip Function
In this article, we will discuss zip() function in python, and how to use it with the help of examples. Later in the article, we will also discusss how to...read more
Difference Between Methods and Functions in Python
Difference Between Methods and Functions in Python
In Python, methods and functions have similar purposes but differ in important ways. Functions are independent blocks of code that can be called from anywhere, while methods are tied to...read more

Endnotes

In conclusion, packing and unpacking arguments in Python is a powerful feature that enables us to pass an arbitrary number of arguments to a function. Using the * operator, we can pack positional arguments into a tuple and pass them to a function. Using the ** operator, we can pack keyword arguments into a dictionary and pass them to a function.

And using the same operators with the corresponding syntax, we can also unpack arguments from tuples or dictionaries and pass them as separate arguments to a function. This feature can simplify and streamline our code, making it more flexible and reusable. If you seek to learn more about Python and practice Python programming, you can explore related articles here.

Explore programming courses

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio