What are *args & **kwargs? And why would we use it?
*args
The *args is a magic variable in Python which allows us to create a
function which takes a non-keyworded variable length arguments in the
form of a tuple
and we simply iterate it to access each arguments.
We
may not know the exact numbers of variables passed in a function
beforehand so *args
helps to resolve this problem.
Actually only * can be used to denote the variables being received in the form of tuples.
*args Example
In the following example, we make a function to multiply for any given numbers passed to the function multiply to illustrate concept of *args
def multiply (*args):
result = 1
# iteration & multiplication
for numbers in args:
result = result * numbers
print(result)
# function call
multiply(4, 5) # outputs 20
multiply(3, 4, 5) # outputs 60
multiply(3, 5, 10, 6) # outputs 900
**kwargs
**kwargs is also a magic variable in Python which allows us to create a function that takes any number of keyword arguments. Arguments can be passed as a key value pairs or in the form of dictionary data type. We use **kwargs when we want to handle named arguments in a function.
**kwargs Example
Following program prints the values of a given keys passed to illustrate the concept of **kwargs
def print_values(**kwargs):
# iteration
for key, value in kwargs.items ( ):
print("Value of {0} is {1}".format(key, value))
# function call
print_values(my_name = "Alex", your_name = "Alice")
Output
Value of my_name is Alex Value of your_name is Alice