In the previous article we have discussed keyword arguments, now we will look at another type of argument that can be provided to functions: Variable length arguments. Many times we want a functionality to be implemented for various different inputs. If we pass two, then we want sum of two variables. We want a sum function to return the sum of any number of elements. How can we implement such a function?
Implementation of Variable Length Arguments
Variable arguments help in the scenario where the exact number of arguments are not known in the beginning, it also helps to make your function more flexible. Variable length arguments are defined by specifying * symbol in front of the variable passed to the function without any space in between.
def sum(*elements):
res=0
for x in elements:
res=res+x
return res
print(sum(10,20))
print(sum(10,20,30))
print(sum(10))
print(sum())
Output:
30
60
10
Once a variable is passed along with the star symbol, it becomes a tuple. This tuple has all the arguments that you pass to the function, we can pass any number of functions and they are received as tuple elements.Whatever arguments we provide can be traversed through the tuple like elements. If we pass no arguments the function will not execute as the tuple is empty.
def sum(init_sum, *elements)
res=init_sum
for x in elements:
res=res+x
return res
print(sum(0,10,20))
print(sum(5,10,15))
Output:
30
30
It specifies that the result should be assigned to the init_sum variable while the rest can be assigned to *elements. When we call this function we assign from print(sum(0,10,20)) statement, the value of sum is initialized as zero and 10,20 are provided as tuple elements.
In the next line the sum initial value is assigned as 5, and then the elements assigned to the tuple are 10 and 15. Both statements provide an end result of 30.
Suppose we want to define keyword variable length arguments
def printDetails(**details):
for d,v in details.items( ):
print(f"{d} is {v}")
printDetails(id=101,name="abc", price=100)
print( )
printDetails(id=102, name="xyz")
Output:
id is 101
name is abc
price is 100
id is 102
name is xyz
Using ** rather than * indicates a keyword variable length argument, and the elements are stored in the form of a dictionary rather than as tuple elements.
Hence we have seen the purpose of Variable Length Arguments in Python, in the next article we will explore Parameter Passing in Python.