Calling a function with unknown number of parameters Python
In python, we can pass an unknown amount of arguments into the function using asterisk notation.
Let's try to create a function sum_up()
with an unknown number of arguments.
def sum_up(*args):
s = 0
for i in args:
s += i
return s
As you see, an argument with an asterisk before will collect all arguments given to this function inside a tuple called args
.
We can call this function that way:
sum_up(5, 4, 6) # Gives 15
But if we want to sum up elements of a list and we need to pass it into the function as arguments...
We can try the following:
l = [5, 4, 6]
sum_up(l)
This won't give an effect we need: args
of sum_up
will look like ([5, 4, 6],)
.
To do what we want, we need to put an asterisk before the argument we're passing:
sum_up(*l) # Becomes sum_up(5, 4, 6)
All you need to do is collect all arguments you want to pass in a list and then put an asterisk before this list passed as an argument inside a call:
args = [service ['good '] , tip ['average']]
ctrl.Rule(*args)