Flexible number of arguments
It is possible to create a function that will accept a flexible amount of arguments. This is useful in scenario where we don’t know ahead of time how many arguments you will be providing to the function.
We just need to type *args inside the parentheses during the function definition that collects all arguments provided during the function call:
The * character instruct Python to store all passed arguments inside the tuple called args. We can then loop through this tuple to access its content.
Consider the following example. We want to sum up all the numbers provided during the function call. However, since we don’t know in advance how many arguments will be provided in the function call, we need to use the *args tuple:
def sum(*args): total = 0 for x in args: total += x return total sum_1 = sum(5, 12) sum_2 = sum(3, 22, 55, 22, 3, 73, 246, 23) sum_3 = sum(1, 44, 223) print(sum_1) print(sum_2) print(sum_3)
The function sum will take all the arguments passed to it during the function call, add them, and return their sum. The function is called three times, and the results are displayed:
>>> 17 447 268 >>>