Introduction
Python is one of the most popular programming languages worldwide. In Python, parameters are a part of function definitions. They enable you to specify certain arguments for a function. The argument can be accepted and applied by the function.
However, it is not possible for you to know at the time of coding what exact use cases may be implemented with your code. As such, for the sake of future programmers and users of your program, it is advisable to pass a variable number of arguments to a function. To do this, you must use special parameters. These are *args and **kwargs. In this tutorial, we will learn all about the *args and **kwargs parameters in Python. We will also learn how to order arguments and how to apply these in function calls.
Prerequisites
In order to be able to follow the steps in the tutorial, there are some prerequisites you need to prepare. First, you need to have Python 3 installed on your server with a programming environment up and running. You also need to have the program for your particular operating system installed (Ubuntu, CentOS, Debian, etc).
What is *args and How does it Work?
Let’s start off by understanding how *args works. The single asterisk version of the parameter is used to send non-keyworded variable-length argument lists to functions. Keep in mind that the asterisk is the most critical element in that parameter.
To understand better, let’s consider an example. Following is a typical function you may find in your code, using two arguments:
1 2 |
def multiply(x, y): print (x * y) |
As you can see, our arguments in the above function are x and y. When calling the function, you will use numbers corresponding to x and y. Let’s say we are passing the integers 5 and 4 for x and y respectively:
1 2 3 4 |
def multiply(x, y): print (x * y) multiply(5, 4) |
Now we can run the code:
1 |
python lets_multiply.py |
The output we will receive will be as follows:
1 2 3 |
Output: 20 |
The output shows that the integers 5 and 4 have been multiplied. This means that the multiply(x, y) function worked.
Now, let’s say we want to eventually multiply three numbers instead of just two. Unfortunately, adding an extra number to the above function will give you an error like this:
1 2 3 4 |
def multiply(x, y): print (x * y) multiply(5, 4, 3) |
1 2 3 |
Output: TypeError: multiply() takes 2 positional arguments but 3 were given |
Therefore, if you have some idea that you may need to add more arguments sometime later, then apply the *args parameter for your convenience. You can use it like this:
1 2 3 4 5 6 7 8 9 10 |
def multiply(*args): z = 1 for num in args: z *= num print(z) multiply(4, 5) multiply(10, 9) multiply(2, 3, 4) multiply(3, 5, 10, 6) |
We simply replaced the x and y function parameters with *args. Running this code will give you the product for every single function call like so:
1 2 3 4 5 6 |
Output: 20 90 24 900 |
Thus, *args is ideal to use when you want to send variable-length argument lists to your function. Because of its capability, you can pass as many arguments as you want to function calls. As such, this parameter allows you to build more flexible code which can accept a good amount of variable, non-keyworded arguments into the function.
What is **kwargs and How does it Work?
Next, we have the double-asterisk version of the parameters which is **kwargs. Unlike the previous form, this parameter allows you to pass keyworded, variable-length argument dictionaries into the function. Similar to *args, the double asterisks are the most critical element of the parameter.
As we did in the previous section, you can add as many arguments as you want. The difference is that you must assign keywords. To understand better, consider the following example. Here, we will start by printing out the **kwargs arguments we want to pass to the function:
1 2 |
def print_kwargs(**kwargs): print(kwargs) |
Now, let’s call the function. As you can see, we added keyword arguments:
1 2 3 4 |
def print_kwargs(**kwargs): print(kwargs) print_kwargs(kwargs_1="Shark", kwargs_2=4.5, kwargs_3=True) |
Running the program at this point will show you this output:
1 |
python print_kwargs.py |
1 2 3 |
Output: {'kwargs_3': True, 'kwargs_2': 4.5, 'kwargs_1': 'Shark'} |
However, there is a possibility that your dictionary data type is unordered. This largely depends on the version of Python 3 you use. For example, any version beyond Python 3.6 gives you the key-value pairs in order. Any version that comes before that will show the output in random order. The dictionary that you create will be called kwargs. Note that you can use and manipulate it like any other dictionary on the system. Let’s see how you can put the **kwargs parameter to greater use and application.
In the following example, we will try to make a new function that will greet a dictionary with names. Our sample dictionary will have two names:
1 2 3 4 5 |
def print_values(**kwargs): for key, value in kwargs.items(): print("The value of {} is {}".format(key, value)) print_values(my_name="Sammy", your_name="Casey") |
Running the program will give you this output:
1 |
python print_values.py |
1 2 3 4 |
Output: The value of your_name is Casey The value of my_name is Sammy |
Similar to the previous example, the dictionaries may appear to be unordered. As such, the order of the names Casey and Sammy may be inverted in some cases.
Next, we will pass additional arguments to the function. This will prove that you can make **kwargs accept any number of arguments you want:
1 2 3 4 5 6 7 8 9 10 11 |
def print_values(**kwargs): for key, value in kwargs.items(): print("The value of {} is {}".format(key, value)) print_values( name_1="Alex", name_2="Gray", name_3="Harper", name_4="Phoenix", name_5="Remy", name_6="Val") |
Running the program will show you this output:
1 2 3 4 5 6 7 8 |
Output: The value of name_2 is Gray The value of name_6 is Val The value of name_4 is Phoenix The value of name_5 is Remy The value of name_3 is Harper The value of name_1 is Alex |
This output may also be unordered. Regardless, these examples show that **kwargs gives your program the flexibility to use a number of keyword arguments.
How to Order Arguments
It is important to keep in mind the set order when ordering an argument in a function or function call. It is as follows:
-
Formal positional arguments
-
*args
-
Keyword arguments
-
**kwargs
Let’s say you are using *args and **kwargs with explicit positional parameters. This means that your function will look like this:
1 2 |
def example(arg_1, arg_2, *args, **kwargs): ... |
On the other hand, using these parameters with names keyword parameters will give your function the following general structure:
1 2 |
def example2(arg_1, arg_2, *args, kw_1="shark", kw_2="blobfish", **kwargs): ... |
Not complying with the set order will give you a syntax error when you run your code. Therefore, it is best to avoid making the mistake in the first place.
How to Use *args and **kwargs in Function Calls
Lastly, we will show you how to use both the parameters to pass arguments into functions. We will begin with an example showing *args:
1 2 3 4 5 6 7 8 |
def some_args(arg_1, arg_2, arg_3): print("arg_1:", arg_1) print("arg_2:", arg_2) print("arg_3:", arg_3) args = ("Sammy", "Casey", "Alex") some_args(*args) |
There are three parameters in this function: arg_1, arg_2, and arg_3. You must create a variable and set it to an iterable. In this case, it will be a tuple. Then, you can pass the variable into the function using the asterisk syntax.
Observe the output when you run the program using the python some_args.py command:
1 2 3 4 5 |
Output: arg_1: Sammy arg_2: Casey arg_3: Alex |
It is possible to change the program to an iterable list data type as well with a different variable as a name. The following code combines *args with a named parameter:
1 2 3 4 5 6 7 8 |
def some_args(arg_1, arg_2, arg_3): print("arg_1:", arg_1) print("arg_2:", arg_2) print("arg_3:", arg_3) my_list = [2, 3] some_args(1, *my_list) |
The output will be as follows on running the program:
1 2 3 4 5 |
Output: arg_1: 1 arg_2: 2 arg_3: 3 |
On the other hand, you can apply keyworded arguments with **kwargs. Make sure to create a variable that is equal to a dictionary. It should have 2 key-value pairs. Here is how we will pass the variable to a function with 3 arguments:
1 2 3 4 5 6 7 8 |
def some_kwargs(kwarg_1, kwarg_2, kwarg_3): print("kwarg_1:", kwarg_1) print("kwarg_2:", kwarg_2) print("kwarg_3:", kwarg_3) kwargs = {"kwarg_1": "Val", "kwarg_2": "Harper", "kwarg_3": "Remy"} some_kwargs(**kwargs) |
Use the python some_kwargs.py command once again to run the program:
1 2 3 4 5 |
Output: kwarg_1: Val kwarg_2: Harper kwarg_3: Remy |
Conclusion
By the end of this tutorial, you should be well versed in what *args and **kwargs are and how they work. You can now apply these parameters to your own code to make your program flexible for future users. These are ideal for situations when you are unaware of how many arguments may be used. Just make sure to be careful about the critical elements of the functions and parameters.
Finally, here are more resources from our blog that will help you work successfully with Python:
- The txt File Format: Working with Plain Text Files in Python 3
- Loops in Python 3: Using Break, Continue, and Pass Statements
- Importing Modules in Python 3: A Comprehensive Guide
- Using Python 3 String Formatters
- Programming with Python 3: How To Go About Constructing Classes and Defining Objects?
Happy Computing!
- How to Deploy WordPress with Persistent Volume on Kubernetes Cluster - March 17, 2023
- Deploying Applications on Kubernetes Using Argo CD and GitOps - October 26, 2022
- Using Node.js Modules with npm and package.json: A Tutorial - October 6, 2022
- Using Ansible to Install and Configure WordPress with LAMP on Ubuntu - September 23, 2022
- Creating Views in the Django Web Application Framework - September 22, 2022