Pass a List to a Function to act as Multiple Arguments
In this article, we will learn how to pass a list to a function to act as multiple arguments in Python. We will understand the basic approach with some custom codes.]
Pass a List to a Function as Multiple Arguments
In Python, functions can take either no arguments, a single argument, or more than one argument. We can pass a string, integers, lists, tuples, a dictionary etc. as function arguments during a function call. The function accepts them in the same format and returns the desired output. Now, we want to pass a list that contains multiple elements and these elements act as multiple arguments of a function. This concept of passing a single list of elements as multiple arguments is known as Unpacking Argument List. We use
*args to unpack the single argument into multiple arguments. We use the unpacking operator
*when arguments are not available separately.
For example,
range() function in Python stores three different arguments - start, stop, and step. If the user does not want to input the values separately, he can write the function call with the
*operator to unpack the arguments out of a list or tuple.
Example:
In this example, my_list is iterable that is passed as an argument. Function definition treats this list as multiple arguments. Python program loops over the given list and uses each element of the list as a separate argument to the function. The below code just unpacks the list using the
*args syntax when defining the function.
#function definition def add(*params): sum = 0 for num in params: sum += num print(sum) #input list my_list = [1,2,3] #function call add(*my_list)
6
Example:
This method is useful when the elements are not predetermined. We can pass multiple elements to a python function without predetermining the formal parameters. This example uses
*args to avoid the code failing when the user does not know how many arguments will be sent to the function. You can use this method when elements in a list are not predetermined.
def calculateTotalSum(*arguments): totalSum = 0 for number in arguments: totalSum += number print(totalSum) # function call calculateTotalSum(5,4,3,2,1)
15
Conclusion
In this article, we used different examples to understand how can we unpack the list elements to use them as multiple arguments. We discussed
*args syntax in Python to unpack the arguments of the list and use them separately in the function body.