*args and **kwargs in Python

*args and **kwargs in Python

 

Arbitrary Arguments are often shortened to *args and Arbitrary Keyword Arguments are often shortened to **kwargs in Python documentations.

*args and **kwargs in Python

Arbitrary Arguments ( *args )

If we are not sure with number of arguments that will be passed in our function, we can use * before the parameter name so that the function will receive a tuple of arguments, and we can access the items accordingly.


#function
def welcome( *match ):
    print(\n Total number of matches are : “,len(match))
    for n in match:
        print(“Score :”,n )


# Passing 9 parameters
welcome(10,9,8,9,7,6,9,8,5)

# Passing 6 parameters
welcome(4,5,9,4,10,5)


Output :


 Total number of matches are :  9
Score : 10
Score : 9
Score : 8
Score : 9
Score : 7
Score : 6
Score : 9
Score : 8
Score : 5

 Total number of matches are :  6
Score : 4
Score : 5
Score : 9
Score : 4
Score : 10
Score : 5

Arbitrary Keyword Arguments ( **kwargs )

If we are not sure with number of keyword arguments that will be passed in our function, we can use ** before the parameter name so that the function will receive a dictionary of arguments, and we can access the items accordingly.


#function
def details( **name ):
    print(“First Name : “ + name[“fname”])

# Passing 2 parameters
details(fname=“Muskan”lname=“Agarwal”)

# Passing 1 parameter
details(fname=“Anchal”)


Output :

First Name : Muskan
First Name : Anchal