Python
In this tutorial we will learn about functions with variable length arguments in Python.
In the Python - Functions tutorial we learned about functions and how to pass value to functions when making function calls. Feel free to recap.
In the following Python program we are calling a function and passing two integer values and it is returning back the sum.
# func
def sum(x, y):
return x + y
result = sum(10, 20)
print(result) # 30
So, the above code will print 30 as output.
Now, imagine we want to create a sum
function that can take any number of arguments (like 2, 3, 4 ...).
The problem with above sum
function is that we can only pass two arguments.
Python allows us to create functions that can take multiple arguments. So, lets create multi-argument functions.
Following is the syntax to create a function that can take variable length arguments.
def func(*args):
#
# body of the function
#
Where, func
is the name of the function and *args
holds variable length arguments.
In the following Python program we are recreating the sum
function but this time we are modifying it to take multiple arguments and print them.
# func
def sum(*args):
print(type(args))
print(args)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)
If we run the above code we will get the following output.
<class 'tuple'>
(10, 20)
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
(10, 20, 30, 40
So, we can see that the args
variable is of type tuple
and we are also able to print all the values that were passed to the function as a tuple.
Since the multiple arguments passed to the function are tuple so we can access them using for loop.
In the following Python program we are printing out the individual argument.
# func
def sum(*args):
for arg in args:
print(arg)
print('sum(10, 20)')
sum(10, 20)
print('sum(10, 20, 30)')
sum(10, 20, 30)
print('sum(10, 20, 30, 40)')
sum(10, 20, 30, 40)
The above code will given us the following output.
sum(10, 20)
10
20
sum(10, 20, 30)
10
20
30
sum(10, 20, 30, 40)
10
20
30
40
So, now that we are able to access the individual argument passed to the function let's go ahead and modify the sum
function that we are working on to return us the sum of the arguments.
# func
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Let's add some checks to the sum
function so that we only add arguments that are numbers.
# func
def sum(*args):
result = 0
for arg in args:
if type(arg) in (int, float):
result = result + arg
return result
print(sum(10, 20.10, "hello")) # 30.1
Feel free to experiment with the above code and modify it as per your imagination.
Looking forward to see you again in the next tutorial. Have fun coding :)
ADVERTISEMENT