Python *Args and **Kwargs Parameter [ Simplest Example]
Python functions are a little bit different from C/C++ functions as they can receive variable parameters using *args and **kwargs parameters.
*args allows a variable number of parameters of the same data type as a parameter. In order to understand the working of *args, lets us explore the example
def sum(a, b): print("sum is", a+b) sum(10,5)
output of the above code is
sum is : 15
The above python function will collapse if you pass 3 parameters or 1 parameter. SO this type of parameters are also known as static parameters.
Python Function to Demonstrate the working of *args parameter
# function to demonstrate the workin of args and kwards paramater # made by : rakesh kumar def sum_values(*args): sum = 0 for x in args: sum += x return sum if __name__ == "__main__": res = sum_values(1, 2, 3, 4, 5, 6, 7, 8, 9) print('Sum of values :', res)
OUtput of above function is
Sum of values : 45
The above function takes all the arguments and add the values in and return to its calling function using return.
Python **kwargs parameter
Python passes variable length non keyword argument to function using *args but we cannot use this to pass keyword argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of keyword arguments to the function.
In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk **.
Python function to explain **kwargs
# python program to demonstrate the use of kwargs arguments in pyhon # made by : rakesh kumar def sum_kwargs(**kwargs): for x, y in kwargs.items(): print('{} and its valiue {}'.format(x, y)) if __name__ == "__main__": sum_kwargs(name='rakesh', school='DAV', salary=50000)
The output of the above function is
name and its valiue rakesh school and its valiue DAV salary and its valiue 50000
Summary of *args and **kwargs:
- *args and *kwargs are special keyword which allows a function to take a variable-length argument.
- *args passes variable number of non-keyworded arguments list and on which operation of the list can be performed.
- **kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.
- *args and **kwargs make the function flexible.
Now I think you have the idea of *args and **kwargs function parameters. if you have any questions, please contact us