Packing and Unpacking Arguments in Python
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.
- Types of Function Arguments in Python
- What are Packing Arguments?
- What are Unpacking Arguments?
- Working of Packing and Unpacking Arguments Together
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
Best-suited Python courses for you
Learn Python with these high-rated online 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 argumentspack_args(1, 2, 3, "Hello", [1, 2, 3])
Output:
<class 'tuple'="">123Hello [1, 2, 3]
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 argumentspack_kwargs(name="John", age=30, country="USA")
Output:
<class 'dict'="">name: Johnage: 30country: USA
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 argumentsargs = (1, 2, 3)add(*args)
Output:
6
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 argumentsperson = {"name": "John", "age": 30, "country": "USA"}print_person(**person)
Output:
Name: JohnAge: 30Country: USA
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}
Output:
39
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.
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
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