Python *args and **kwargs

Today we are discussing two special types of function arguments *args and **kwargs.
In Python we have three different types of function arguments:
Formal arguments for example arg in the function definition def func(arg):.
Variable length of non-keyworded arguments, for example, *args in def func(*args):
Variable-length keyworded arguments, for example, **kwargs in def func(**kwargs):

What are *args and **kwargs and how do we use it in Python?

*args and **kwargs are variable-length function arguments that are used to input variable-length inputs to a function. This is used when we require several inputs than initially defined. For example, consider the code below:

def add(a,b):
 sum = a+b
 print(sum)
add(2,3)

Output:

5

Here we have defined two formal parameters inside the function, ‘add’, hence this function can add only two numbers. If we want to add more than two numbers we have to modify the function definition. This won’t be a convenient method every time. This is the case when we use *args and **kwargs as the function arguments. These parameters allow the user to input n number of arguments for the function.

*args

*args is the non-keyworded variable-length argument. To use this argument we use ‘*’ symbol followed by the argument name. It is of type tuple i.e a tuple is passed as an argument to the function. An example showing the use of *args:

def multiply(*args): 
    result = 1
    for argument in args:
        result *= argument 
    print(result) 
multiply(2,3,8,5,9)
multiply(4,5)
multiply(5,5,3)

Output:

2160
20
75

In the above example, we have used *args as the argument for the multiply function. This *args allows us to take a different number of arguments each time we call the function. Inside the function, we run a loop to multiply all the arguments passed within the function and stores the output in the variable, ‘result’.

**kwargs

**kwargs is the keyworded variable-length argument. Keyworded arguments refer to the arguments where we pass the variable names along with the variables. To use this argument we use ‘**’ symbol followed by the argument name. It is of type dict i.e a dictionary is passed as an argument to the function. An example showing the use of **kwargs:

def details(**kwargs):
    for key, value in kwargs.items():
        print("{} : {}".format(key,value))
print("-----------------------1st customer---------------------")
details(Name="David", Sex='M', Age=54)
print("-----------------------2nd customer---------------------")
details(Name="Shreya", Sex='F', Age=36, Occupation='Nurse', Country='India')

Output:

-----------------------1st customer---------------------
Age : 54
Name : David
Sex : M
-----------------------2nd customer---------------------
Occupation : Nurse
Age : 36
Country : India
Name : Shreya
Sex : F

In the above code, the use of **kwargs argument has allowed us to pass a different number of inputs each time we called the function. We passed the variable name along with the variable in the form of a dictionary.

Note: args and kwargs are the names that are conventionally used for the variable-length arguments. Though we can use any other name that is followed by a * or **. The only reason for using args and kwargs is that they make the code more readable.

Why is * or ** symbol used for the variable-length arguments:

The single(*) and double(**) asterisk symbols are the unpacking operators. These unpacking arguments help to unpack all the different elements of the tuple or list as single, individual parameters. For example, take the following code.

list1=[3,4,5]
print("printing the list")
print(list1)
print("printing the list using unpacking operator(*)")
print(*list1)

Output:

printing the list
[3, 4, 5]
printing the list using unpacking operator(*)
3 4 5

The asterisk operator unpacks the elements of the list and prints all the contents separately. This is the reason we use this operator with the function parameters while defining a function with variable length arguments. When we pass variable-length inputs to the function, the * operator unpacks all the inputs and treats them as different inputs. Hence we use the * and ** operators.

Leave a Reply

Your email address will not be published. Required fields are marked *