*args in python

Whenever there is any function that accepts arguments, the number of arguments passed while calling the function should always match the number of arguments in the function. If we violate this the code throws an error. Let us look at this with a simple example. Consider the following code.

function in python

This will print 10 as the output. But, what happens if we pass more than 2 numbers to the function like this.

Incorrect function calling

This will throw an error message like this,

TypeError: addition() takes 2 positional arguments but 3 were given

we will get a TypeError like this. But what if we are uncertain of the values that we are going to pass? what if we want to add different length of numbers each time? What happens if we want to add 5 numbers the first time, 6 numbers the next and so on? what if the total numbers that we want to add differ always?

*args comes in handy in a situation like that. In fact it is not even *args we can give any name we want. We can give like ‘*numbers’ or ‘*data’ etc.

Let us look at this with an example code.

*args in python

This will output


By this way we can give any number of arguments to the function. It will treat them as an array and hence we have to iterate to get those values.

We can use this method to pass variable number of arguments. Learn the basics, code better.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *