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.

def average(a , b, c): ''' Function To calculate the average of 3 numbers ''' return (a+b+c)/3

Now let’s use this function,

avg = average(1 , 2, 3)

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

**Advertisements**

23,1,3,4,5,6,7

or

23,1,3,16,78

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.

def calculateAverage(*args): .... ....

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.

def calculateAverage(*args): ''' Calculates the average of n numbers | Accepts variable length arguments ''' # get the number of total arguments passed argCount = len(args) if argCount > 0 : sumOfNums = 0 # Iterate over all the arguments and calculate average for elem in args : sumOfNums += elem return sumOfNums / argCount else: return 0

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

# Calculate the average of 3 numbers avg = calculateAverage(4, 5, 4)

Value of avg will be 4.333333333333333

# Calculate the average of 7 numbers avg = calculateAverage(23,1,3,4,5,6,7)

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.

argCount = len(args)

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

for elem in args : sumOfNums += elem

## 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.

def publishError(startStr, endStr, *args): ''' Publish n number of Error | | Accepts variable length arguments formal parameters ''' print(startStr) for elem in args : print("Error : " , elem) print(endStr)

Let’s call this function,

publishError("[Start]" , "[End]" , "Invalid params", "Unknown Error")

Output:

[Start] Error : Invalid params Error : Unknown Error [End]

**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.

publishError("[Start]" , "[End]" , [1, 2, 4], ("Hello", "Hi"), "Sample error")

Output:

[Start] Error : [1, 2, 4] Error : ('Hello', 'Hi') Error : Sample error [End]

**Complete example is as follows,**

def average(a , b, c): ''' Function To calculate the average of 3 numbers ''' return (a+b+c)/3 def calculateAverage(*args): ''' Calculates the average of n numbers | Accepts variable length arguments ''' # get the number of total arguments passed argCount = len(args) if argCount > 0 : sumOfNums = 0 # Iterate over all the arguments and calculate average for elem in args : sumOfNums += elem return sumOfNums / argCount else: return 0 def publishError(startStr, endStr, *args): ''' Publish n number of Error | | Accepts variable length arguments formal parameters ''' print(startStr) for elem in args : print("Error : " , elem) print(endStr) if __name__ == '__main__': # Calculate the average of 3 numbers avg = calculateAverage(4, 5, 4) print("Average : " , avg) # Calculate the average of 7 numbers avg = calculateAverage(23,1,3,4,5,6,7) print("Average : " , avg) # Calculate the average of 0 numbers avg = calculateAverage() print("Average : " , avg) publishError("[Start]" , "[End]" , "Invalid params", "Unknown Error") publishError("[Start]" , "[End]" , [1, 2, 4], ("Hello", "Hi"), "Sample error")

**Output:**

Average : 4.333333333333333 Average : 7.0 Average : 0 [Start] Error : Invalid params Error : Unknown Error [End] [Start] Error : [1, 2, 4] Error : ('Hello', 'Hi') Error : Sample error [End]