+ 1
Python - Why do a and c have the same address?
def f(x, y = []): y.append(x) return y a = f(1) b = f(2,[]) c = f(3) print(a) print(b) print(c) print(a is c) Output: [1, 3] [2] [1, 3] True Why do a and c share the same memory address (while b does not)? --> Does the number of arguments have something to do with it?
2 odpowiedzi
+ 3
y has only 1 default value. If you change the value, it may affect the result, when you next time want to call the function.
f(2, []) won't use the default value.
+ 2
The answer of Seb TheS is right. I want to add that the default arguments are evaluated once the function is defined, which means that the default parameter is an object in memory used by the function if the value is not passed when the function is called. Another way to understand this, just modify your function to:
def f(x, y = None):
if y is None:
y = []
y.append(x)
return y
Calling this function without providing a second parameter will create a new object for y. So if you run your code on this function, you will get:
[1]
[2]
[3]
False
I hope you get the difference between the two functions.