Why not use a variable list as a parameter, or a variable list as a parameter?
The following code:
def test_list(my_list=[]): my_list.append(1) return my_listprint(test_list())print(test_list())print(test_list())
Output:
[1][1, 1][1, 1, 1]
Intuitively, the output must be [1]. We know that a rule is not to use variable variables as parameters, but why?
Function has a built-in function func_defaults that displays the default variables.
>>> test_list.func_defaults([],)
You can see that the func_defaults attribute of the test_list function points to a tuple, which has a [] element, that is, the default value of the function parameter my_list. If it is wrong, the my_list point to the region is variable.
Run the evaluate function test_list () and check whether the tuples pointed to by func_defaults have changed.
>>> test_list()[1]>>> test_list.func_defaults([1],)
The default value of my_list is [1]. this is my_list pointing to a variable list, and the python function is passed by reference by default. When the function executes the append operation on my_list, it also changes the list of the tuples pointed to by func_defaults in my_list. During the next execution, the default value of my_list is changed to ([1],).
Take a look at python tutor:
If the function needs to accept a list, set my_list to None.
def test_list(my_list=None): if not my_list: my_list = [] my_list.append(1) return my_list