In the Python function, you can also define mutable parameters.
For example: Given a set of numbers a,b,c ..., please calculate a2 + b2 + C2 + ....
To define this function, we must determine the input parameters. As the number of arguments is uncertain, we first think that we can put a,b,c ... Passed in as a list or tuple, so that the function can be defined as follows:
def Calc (numbers): = 0 for in numbers: = sum + N * n return sum
But when called, a list or tuple needs to be assembled first:
>>> Calc ([123])>>> Calc (13 5 7 ))
If you take advantage of mutable parameters, the way you call a function can be simplified to this:
>>> Calc (123)>>> Calc (1 3 5 7 )
So, let's change the parameter of the function to a variable parameter:
def Calc (*numbers): = 0 for in numbers: = sum + N * N return sum
When you define a mutable parameter and define a list or tuple parameter, just precede the parameter with an * number. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters:
>>> Calc (12)5>>> calc ()0
What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:
>>> nums = [123]>>> Calc (nums[0], nums[1], nums[2])
This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to precede the list or tuple with an * number, the list or tuple of the elements into a variable parameter to pass in:
>>> nums = [123]>>> Calc (*nums)14
Python can be in the tuple, list, dict before the * number, the role is to solve the variable into a number of independent parameters, passed in the function, there is a similar two asterisks, is to solve the dictionary as a separate element as a formal parameter.
def Add (A, b): return a+ = [4,3]print Add (*data)#equals to print Add (4, 3) data = {'a'b ': 3}Print Add (* *data)#equals to print Add (4, 3)
Variable parameters in a Python function