def foo1(x=[]): x.append(1) print(x) def foo2(): x = [] x.append(1) print(x) Why, when repeatedly calling the function foo1 () (without arguments), the output is:
[1] [1, 1] [1, 1, 1] ... def foo1(x=[]): x.append(1) print(x) def foo2(): x = [] x.append(1) print(x) Why, when repeatedly calling the function foo1 () (without arguments), the output is:
[1] [1, 1] [1, 1, 1] ... The difference is that the first function can take 1 argument, the second does not accept arguments. I advise you to read brief information about functions in Python.
The behavior you are asking for occurs for such a reason that the default value (empty list) is calculated once when the function has been compiled, then it is used for each function call. To avoid this behavior and get an empty list with each call, change the code as follows:
def foo1(x=None): if x is None: x = [] x.append(1) print(x) Why, when repeatedly calling the function foo1 () (without arguments), the output is
Arguments are created by default once and the function itself is still alive. Do not use mutable objects (such as lists, dictionaries) as default arguments.
If you don’t transfer anything to foo1() , then you have only one list x where you add new elements to each call.
foo2() at each call creates a new list and adds one element to it.
In a nutshell, so:
The default argument will be the same object , even with different function calls. That is, if you change this object in one function call, it will save this new value on the next call.
This does not appear when you use immutable objects (numbers, strings, tuples, etc.) as the default. But this becomes noticeable if you use mutable objects (lists, sets, etc.) as the default.
Therefore, it is usually not recommended to use mutable objects as a default argument.
Source: https://ru.stackoverflow.com/questions/534663/
All Articles