In this article we will discuss how to define a function in python that can accept variable length arguments.

Suppose we have a function to calculate the average of 3 numbers i.e.

Now let’s use this function,

But what if we want to calculate the average of numbers more than 3 in counti.e.


We can not use the above defined average() function for this because it accepts only 3 arguments. So, in that case either we need to create more function or use default arguments etc.

But there is an easy solution, for this kind of scenario we can create a function that accepts n number of arguments. Let’s see how to do that,

Define function that can accept variable length arguments

Python provides a mechanism by which we can receive variable length arguments in function i.e with symbol * .
Prefixing this symbol * with any parameter in function definition will make that parameter handle variable length arguments i.e.

Now this function can accept variable length arguments and will store all the arguments in a tuple with name args. Generally this parameter name is args but we can provide any name.

Let’s create a function that can calculate the average of variable length numbers i.e.

Now we can call this function with variable length arguments i.e.

Value of avg will be 4.333333333333333

Value of avg will be 7.0

Inside this function args will be of type tuple. So, we can get the count of total arguments passed by calling len() function of tuple args i.e.

We can also iterate over the all arguments by iterating over the tuple i.e.

Important points about *args

Positioning of parameter *args

While defining a function we can add other parameters too along with *args. But we need to make sure that parameter *args should always be after formal arguments i.e.

Let’s call this function,


Variable length arguments can be of any type

In parameter *arg , we can pass arguments of different types. For example, lets pass a list , a tuple and string as arguments in above function’s *args parameter i.e.


Complete example is as follows,




Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.