Python : *args | How to pass multiple arguments to function ?

Passing multiple arguments to function in Python.

In this article we will discuss how we can pass multiple arguments  to function using *args in Python.

Let’s say if we want to calculate average of four numbers by a function e.g avg(n1,n2,n3,n4) then we can calculate average of any four numbers  by passing some numbers arguments.

Like

# Program :

def avg(n1,n2,n3,n4):
    # function to calculate average of 4 numbers
    return (n1+n2+n3+n4)/4
average = avg(10,20,30,40)
print(average)
Output :
25.0

But what if we want to calculate average of 10 numbers then we can’t take the above function. Here, in this article we shall define a function in python which can accepts any number of arguments. So, let’s start the topic to know how we can achieve this.

Defining a function that can accept variable length arguments :

We can give any number of arguments in function by prefixing function with symbol ‘*‘.

# Program :

def calcAvg(*args):
    '''Accepts variable length arguments and calculate average of n numbers'''
    # to get the count of total arguments passed
    argNums = len(args)
    if argNums > 0 :
        sum_Nums = 0
        # to calculate average from arguments passed
        for ele in args :
            sum_Nums += ele
        return sum_Nums / argNums
        print(sum_Nums)
    else:
        return 
if __name__ == '__main__':
    avg_Num = calcAvg(10,20,30,40,50)
    print("Average is " , avg_Num)
Output :
Average is 30.0

Important points about *args :

Positioning of parameter *args :

Along with *args we can also add other parameters. But it should be make sure that *args should be after formal arguments.

Let’s see the representation of that.

# Program :

def publishError(startPar, endPar, *args):
# Accepts variable length arguments and publish error
    print(startPar)
    for el in args :
        print("Error : " , el)
    print(endPar)    
publishError("[Begin]" , "[Ends]" , "Unknown error")
Output :
[Begin]                                                             
Error :  Unknown error                                               
[Ends]

Variable length arguments can be of any type :

In *arg we can not only pass variable number of arguments, but also it can be of any data type.

# Programs :

def publishError(startPar, endPar, *args):
# Accepts variable length arguments and publish error
    print(startPar)
    for el in args :
        print("TypeError : " , el)
    print(endPar)    
publishError("[Begin]" , "[Ends]" , [10, 6.5, 8], ('Holla','Hello'), "")
Output :
[Begin]                                                             
TypeError :  [10, 6.5, 8]                                           
TypeError :  ('Holla', 'Hello')                                     
TypeError :                                                         
[Ends]