In this section, we will learn about functions with single asterisk * operator.
Extracting and Gathering Positional Arguments with Asterisk * Operator
Sometimes we don’t know how many arguments a function will take in the future when that function is being called. For example, it might get called with one argument in one statement, but then in another call it takes several arguments! Basically, the arguments of a function become arbitrary!
Now, in order to handle such type of function with arbitrary arguments, python provided a method by which we can create a function that is able to take any random number of arguments.
Python Gathering Positional Arguments with Asterisk * Operator
In order to create a function capable of taking an arbitrary number of arguments, the last parameter of that function should be prefixed with an asterisk `*`.
def functionName( firstParameter, *secondParameter):
In this example, the first parameter of this function is a positional parameter that we’ve seen so far.
But the second parameter represents a tuple! In the tuple section we will learn about tuples in greater details but for now just remember that tuples are objects that are capable of holding arbitrary number of values!
So here if we call the `functionName` and pass multiple arguments to it, the first argument will be passed to the `firstParameter` and the rest will be assigned to the `secondParameter` which is a tuple. So the rest of arguments become the elements of this tuple object.
Note: the tuple parameter always comes as the last parameter of the function.
Example: gathering positional arguments with * operator
def add(*values): value = 0; for num in values: value +=num print(value) add(1,2,3,4,5,6,7) add(1,2) add(1) add(1,2,3,4)
28 3 1 10
In this example, the `add()` function has one parameter, and that represents a tuple object. This means we can call this function with any number of arguments and they will be assigned as the elements of the tuple object.
Note: if the function had more parameters, then the arguments of the function first fill the parameters and then the rest of arguments (if any) would be sent to the tuple object.
After that, within the body of the `add` function, we used the `for` loop to take out (extract) the elements of this tuple object and add them together to get the final result.
Note: you’ll learn more about the `for` loop and `tuples` in later sections.