1. Home
  2. Docs
  3. Python 201
  4. *args and **kwargs in Python

*args and **kwargs in Python

 
In this lesson you will learn about *args and **kwargs.
 

In Python,we have four types of arguments.
 

Four types of Arguments

 
1. Required(mandatory) arguments

2. Optional arguments(default values)

3. Variable positional arguments

4. Variable keyword arguments

 

1. Required arguments

 

Where its must to pass the arguments

to the function.
 
Ex 1:
 
Function to add two numbers

add functon takes two arguments, and returns the result

def add(num1, num2):
    
    return num1 + num2
 
sum = add(10,20)

output:
    
30

  

when add() is called, its must to pass values for both num1, num2.

Otherwise TypeError exception is raised.

sum(10)

output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-38edd8aedd79> in <module>()
----> 1 sum = add(10)

TypeError: add() missing 1 required positional argument: 'num2'

    

  

2. Optional arguments

 

Where a funciton is defined with default values for argument(s),

passing values during function call is optional.
   

def add(a = 10, b = 20):
    
    print("a and b are :",a,b)
    
    return a + b



#add called with no arguments
sum1 = add()

print("sum1 is :", sum1)
 
#add called with one arguments 
 
sum2 = add(30) 
 
print("sum2 is :", sum2)
 
#add called with two arguments
 
sum3 = add(60, 50) 
 
print("sum3 is :", sum3)
 
 
output:
 
a and b are : 10 20
    
sum1 is : 30
    
a and b are : 30 20
    
sum2 is : 50
    
a and b are : 60 50
    
sum3 is : 110

  

Variable arguments in Python

 
In the above exmple, you have seen,

add() takes, definite number of arguments,

i.e it takes two arguments.

Usually most functions are designed,

to work on fixed set of arguments.

But in some cases you need a function,

to handle any number of arguments.

In Python its possible to have functions,

which takes any number of arguments.

They can be either variable positional or keyword arguments.

Python has special notation for these two types.

*args – any number of positional arguments

argument name starts with ( * ), args is just convention

you can use any valid identifier, ex. *any_args

*args is a tuple,

**kwargs – any number of keyword arguments

argument name starts with ( ** ), kwargs is just convention,

you can use any valid identifier, ex. **varing_aguments.

**kwargs is a dictionary.

 
Let’s explore these more with examples.

 

3. Variable positional arguments

functions are defined using *args as a parameter.

Lets see an example of this,

Ex 1:

Print arguments.

  

def print_args(*args):

  print(args)


print_args()

print_args(1)

print_args(1,2,3,4)

output:

()

(1,)

(1, 2, 3, 4)

  

Notice, we have made three print_args() function calls,

with zero, one and four arguments.
 
Ex 2:
 
Functions takes series of numbers and returns their sum.
  

def sum_numbers(*args):
    
    sum = 0
    
    for i in args:
        
        sum += i
        
    return sum
 

# passing 6 arguments

sum_numbers(1,2,3,4,5,6)

output:
 
21

# passing only two arguments

sum_numbers(1,2)

output:

3

# passing no arguments
 
sum_numbers()

output:

0

  

In the above example sum_numbers takes variable number of arguments.

 

4. Variable keyword arguments
 
function is defined with **kwargs as parameter.

during function call, pass zero or more number of keyword arguments,

with key value pair passed to funciton.

 
Ex 1:
 

sum_numbers(1,2)
   
def user_details(**kwargs):
    
    for k ,v  in kwargs.items():
        
        print("Keyword args : %s = %s" %(k,v)) 
 
  
output:
 
# passing one key-value pair

user_details(name='Alex')
 
output:

Keyword args : name = Alex
 
# passing three key-value pairs

user_details(name ="John", age=23, pwd ='capital')
 
output:

Keyword args : name = John
    
Keyword args : age = 23
    
Keyword args : pwd = capital
    

  

All types of arguments in one function

 
Below example showing all arguments together.
  

def func_arg_options(req, opt ='abc', *args,**kwargs):

    print("req arg  :", req) 
 
    print("opt arg  :", opt) 
 
    for arg in args:
        
        print("Positional args :", arg) 
 
    for k ,v  in kwargs.items():
        
        print("Keyword args : %s = %s" %(k,v)) 
 
 
func_arg_options(15, 'xyz', 'another', name='Alex')
 
output:
 
req arg  : 15
    
opt arg  : xyz
    
Positional args : another
    
Keyword args : name = Alex
 
 
# passing required and keyword arguments

func_arg_options('change', age=23, pwd ='capital')
 
output:

req arg  : change
    
opt arg  : abc
    
Keyword args : age = 23
    
Keyword args : pwd = capital

  

order of arguments

 
at function call, order of positional and keyword arguments matters.

Arguments have to be passed in this order.

required, optional, positional args, and keyword arguments.

 

Lets pass keyword argument before positional argument and see.

 
Ex 1:
  

func_arg_options(15, 'xyz', name='Alex', 'another')
 
output:
    
File "", line 10

func_arg_options(15, 'xyz',name='Alex', 'another')

^
SyntaxError: positional argument follows keyword argument
  

  
in the above example, order is not mentained, keyword argument is

passed before all the positional arguments.