/  Technology   /  What are *args and **kwargs in python functions?

What are *args and **kwargs in python functions?

What are *args and **kwargs in python functions?

Let us first consider this piece of code which has a function named summation() which adds up numbers.

Now, what if we pass more than two arguments to the summation() function. Look at this,

We can see that we’ve got TypeError.

Now to achieve this, Python has enabled with something called *args, **kwargs.

Using these we can pass a variable number of arguments to a function.

*args (Non-Keyword Arguments):

This allows us to pass a variable number of non-keyword arguments to a function. We should add an asterisk(*) before the parameter name to pass variable length arguments. It makes use of a tuple for argument passing and these passed arguments again make a tuple with the same name as the parameter excluding asterisk(*) inside the function.

We used *num as a parameter which allows us to pass variable-length argument lists to the summation function. We passed 3 different tuples as an argument to the function. These tuples are of variable length.

 

**kwargs (Keyword Arguments):

While using *args, we won’t be able to pass a keyword argument. For this to happen, Python has come up with a solution called **kwargs, which allows us to pass the variable length of keyword arguments to a function.

We should add a double asterisk ** before the parameter name to denote kwargs type of argument. It makes use of a dictionary for argument passing and these passed arguments again make a dictionary with name same as the parameter excluding double asterisk ** inside the function.

We have a function info() with **data as a parameter. We passed two to the info() function dictionaries with variable argument length. 

 

 

 

 

Leave a comment