/  Technology   /  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.

 

Example:

def summation(p,q):
   print("sum:",p+q)

summation(10,20)

Output:

 

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

 

Example:

def summation(p,q):
   print("sum:",x+y+z)

summation(2,4,6,8,10)

Output:

 

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):

Example:

def summation(*num):
   sum = 0

   for n in num:
      sum = sum + n

   print("Sum:",sum)

summation(2,5)
summation(4,8,12,16)
summation(1,3,5,7,9,11,13,15,17)

Output:

 

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.

 

Example:

def info(**data):
   print("\nData type of argument:",type(data))

   for key, value in data.items():
      print("{} is {}".format(key,value))

info(State ="Telangana", Capital="Hyderabad")
info(State ="Andhra Pradesh", Capital="Amaravathi", Population="4.94 crores", State_Code="37")

Output:

 

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