*args and **kwargs in Python

PythonServer Side ProgrammingProgramming

When we define a function in a python program, the purpose is to execute the code again and again by supplying different values to the function's arguments. One challenge in this design is, what if we are not sure about the number of arguments we want to process each time we call that function. This is where the special arguments called **args and **kwargs are needed. Let's look at them one by one.

*args

The *args enables us to use variable number of arguments as input to the function. In the below example we are finding out the result of multiplication of a series of numbers. The count of these numbers vary each time we call the function.

Example

def findproduct(*many_nums):
result = 1
for num in many_nums:
result = result * num
print("Multiplication result:",result)

findproduct(3,9)
findproduct(2,11,10)

Output

Running the above code gives us the following result −

('Multiplication result:', 27)
('Multiplication result:', 220)

**kwargs

Next, there are scenarios when we want to pass keyword arguments, which are basically key-value pairs as arguments to a function.

Here again, we can pass the variable number of such keyword arguments to the function. Such arguments are named as **kwargs. Please note there are two asterisks when using such arguments. In reality, such keyword arguments are passed on to the program as a python dictionary which holds a number of key-value pairs.

Example

def country_details(**state_info):
   print('\n\n')
   for k,v in state_info.items():
      print("{} is {}".format(k,v))

country_details(StateName="Telangana", Capital="Hyderabad",Population=3400000)
country_details(StateName="Andhra Pradesh", Capital="Amaravati",Population=1000000,ForestCoverage="30%")

Output

Running the above code gives us the following result −

StateName is Telangana
Population is 3400000
Capital is Hyderabad

StateName is Andhra Pradesh
Population is 1000000
ForestCoverage is 30%
Capital is Amaravati
raja
Published on 08-Jul-2019 18:25:19
Advertisements