To understand python *args and **kwargs first, we need to know some common problems we face while programming in python and how *args and **kwargs solve them?

Examine the following python code:

Output

Notice that we have to write a separate function for adding the different number of arguments. We can simplify this by using a list and sum method.

Output

The little burden of using a list, but still we can do it in a more simple way using *args.

What is *args in Python?

*args is a Non-Keyword Argument which can accept the variable number of arguments and stores them as a tuple.

Output

Thus helps in making a function more flexible in terms of accepting arguments.

Output

What to do? to pass variable and different types of arguments to a function.

In this **kwargs comes handy. Let’s see what is it?

What is **Kwargs in Python?

**kwargs is a Keyword argument which can accept different types of arguments and stores them as a dictionary.

Output

Without **kwargs:

Output

With **kwargs:

Output

It allows a function to accept more than one type of arguments thus makes them more flexible in terms of types of arguments.

Output

Note: we can use any names instead of args and kwargs, what makes them meaningful is * (single asterisk) to make it Non-Keyword Argument and ** (Double asterisks) to make it Keyword Argument.

Hope now you got little idea about *args and **kwargs in python and will be able to use it in your programs. Any doubts then comment below.

Leave a Reply

Close Menu