Understanding *args and **kwargs in Python

In Python programming, if you want to pass the variable number of arguments to a function you can do this by using special symbols. The two special symbols are given below.

  • *args (Non-keyword arguments)
  • **kwargs (Keyword arguments)

In this article, you will learn about *args and *kwargs and their usage in Python programming.

What do you mean by the variable number of arguments to a function

The variable number of arguments means you don’t know how many arguments a user will pass to the function. For example, suppose you want to make a program that takes two numbers from a user and returns their sum.

def add_two(a,b):
    return a+b

This will print the sum of 8 and 3 here the number of arguments is fixed i.e. 2. In a variable number of arguments, the user can pass any number of arguments to the function.

Now in this example, what happens when a user wants to add three or more numbers he will pass 3 or more arguments to this function. Since function takes two arguments you will get the error like TypeError: add_two() takes two positional arguments but 3 were given.

Now let’s see how we can fix this by using *args and **kwargs in our program.

Python *args

If you are not sure about the number of arguments then use *args as a parameter while defining the function this will allow a user to pass a variable number of non-keyword arguments to the function.

The syntax is to use * with parameter name to take a variable number of arguments but by convention, it is often used with the args word. The passed arguments make a tuple inside the function.

Now see the given program –

Example 1:

def adder(*args):
for n in args:
return sum

Here you can enter any number of arguments the function will calculate their sum and return it.

Example 2:

The following example shows the use of *args with normal parameters.

def adder(num, *args):

When you execute this it will print one positional argument i.e. 5 and a tuple or variable arguments. You can see the output in the given image –

Please keep in mind always use normal parameters first and then use the variable for entering a variable number of arguments otherwise you will get an error.

Python **kwargs

A keyworded argument is where you provide a name to the variable when you pass it to a function. You can think of it as a dictionary that maps a keyword to a value.

The **(double star operator) with a parameter is used to pass a keyworded variable length of arguments. By convention ** is often used with kwargs word but you can use any other name also.

For example –

def func(**kwargs):
   for k,v in kwargs.items():

When you run this program you will see –

The *args and **kwargs keywords make a function flexible. Now if you have any doubt then leave it in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.