Today, we'll discuss the use of *args and **kwargs in Python along with some examples.
*args
Let's define a function to add numbers in Python:
def add(a):
print(a + a)
add(3)
Output:
6
then call the function like this,
add(3,4)
we will get the error as shown below,
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes 1 positional argument but 2 were given
The function add is designed to accept only one parameter but in the later statement we passed two which resulted in the above error. To solve this, we need to modify the function to accept two arguments and print its sum as:
def add(a, b):
print(a + b)
add(3,6)
output :
9
If we need to add more than two numbers, we should keep modifying the function to accept the exact number of arguments.
This is where *args can be really useful because it allows you to pass a varying number of positional arguments. Take the following example:
def add(*args):
result = 0
print(args, type(args))
for x in args:
result += x
print('Sum = ',result)
add(3,6,7)
output:
(3, 6, 7) <class 'tuple'>
Sum = 16
Note that args is just a name(commonly used). You can choose any name that you prefer, such as num:
def add(*num):
result = 0
print(num, type(num))
for x in num:
result += x
print('Sum = ',result)
add(3,6,7)
**kwargs
**kwargs stands for keyword arguments. The only difference from args is that it uses keywords and returns the values in the form of a dictionary. In the function, we use the double-asterisk (**) before the parameter name to denote this type of argument.
def total_marks(**kwargs):
print(kwargs, type(kwargs)
total_marks(science=100, english=80))
output:
{'science': 100, 'english': 80} <class 'dict'>
Now, let's complete the total_marks() function to return the total mark.
def total_marks(**marks):
total = 0
for mark in marks.values():
total += mark
print('total mark = ', total)
total_marks(science=59, english=80)
output:
total mark = 139