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.
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]
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.