Hi everyone, In this tutorial, we will see how to use *args and **kwargs in our Python code to make it more flexible using examples.

Using *args

When we are not sure about the number of arguments that will be passed in the function call or if there is no fixed number of arguments that are passed then we can use the special symbol * before the parameter name in the function declaration. *args is a basic conventional name that is often used to maintain consistency and its usage is not mandatory.

The type of *args will be of class ‘tuple’, therefore, all arguments are elements of a tuple.

Example –

Suppose we want to create a function to concatenate 2 lists.

def concat(lst1,lst2):
    new_list=lst1+lst2
    return new_list

list1 = [1,2,5,7]
list2 = ["one","two","three","four"]
res = concat(list1,list2)
print("Concatenated list:",res)

Output:

Concatenated list: [1, 2, 5, 7, 'one', 'two', 'three', 'four']

If we want to concatenate several lists then we need to modify the function according, but using *args we can implement this for any number of lists. Let’s see the code to do this.

def concat(*args):
    new_list=[]
    for lst in args:
        new_list=new_list+lst
    return new_list

list1 = [1,2]
list2 = ["one","two","three"]
list3 = [0.0,"Hello","world"]
res = concat(list1,list2,list3)
print("Concatenated list:",res)

Output:

Concatenated list: [1, 2, 'one', 'two', 'three', 0.0, 'Hello', 'world']

Using **kwargs

The functionality of args is very much similar to the *args that we have discussed, but **kwargs accepts the arguments as key-value pairs or simply the variable number of named arguments. Similar to args, kwargs is a basic conventional name that is often used to maintain consistency and its usage is not mandatory and we can use ** operator before the parameter name.

The type of *kwargs will be of class ‘dict’, therefore, all keyowrd argument and their values are key-value pairs of a dictionary.

Example –

Suppose we want to create a function that will print names of students with the given roll number.

We will use the ** operator to achieve the same.

def get_students(**students):
    for r, name in students.items():
        print("Name of student whose Roll no. {} is {}.".format(r,name))
    return

get_students(CS100='Kunal',CS101='Rohan',CS102='Abhishek')

Output:

Name of student whose Roll no. CS100 is Kunal.
Name of student whose Roll no. CS101 is Rohan.
Name of student whose Roll no. CS102 is Abhishek.

Till now we have seen how to use *args and **kwargs in our Python program, Let’s see an important aspect of the ordering of arguments in case we want to use these together.

Ordering of Arguments

It is important to use the correct ordering of different types of arguments in the function definition, which is given below from first to last. Any change in order will result in an error.

  • Normal positional arguments
  • *args
  • Normal Keyworded arguments
  • **kwargs

Example –

Creating a function that takes all types of arguments in order and prints them.

def ordering(first_pos,*args,first_name,**kwargs):
    """ first_pos : Normal positional argument -> a
        *args -> 1,2
        first _name : Normal named argument
        **kwargs -> CS101, CS102
    """

    # printing all types of arguments 
    print("Normal positional argument: ",first_pos)
    print("*args arguments: ",*args)
    print("Normal named argument: ",first_name)
    print("**kwargs: ",kwargs)

a="Hello World"
ordering(a, 2, 4, 
    first_name = 'This is Named arg', 
    CS100='Kunal',CS101='Rohan',CS102='Abhishek')

Output:

Normal positional argument: Hello World
*args arguments: 2 4
Normal named argument: This is Named arg
**kwargs: {'CS100': 'Kunal', 'CS101': 'Rohan', 'CS102': 'Abhishek'}

In this tutorial, we see how to use *args, **kwargs and their ordering in Python. If you have any doubts, feel free to ask in the comment section below.

Resources

Happy Learning 🙂