1
def test(x, l=[]):
l.append(x)
return l
y = [1, 2, 3, 4]
r = test(7, y)
print(r)
Execution result of 1
[1, 2, 3, 4, 7]
2
def test(x, l=[]):
l.append(x)
return l
r = test(100)
print(r)
r = test(100)
print(r)
Execution result of 2
[100]
[100, 100]
I intended to do the same process twice, The second time, 100 becomes two.
This happens because the list is passed by reference. Because it often leads to bugs Do not pass by reference, such as lists and dictionaries, as default arguments.
So write as follows.
3
def test(x, l=None):
if l is None:
l = []
l.append(x)
return l
y = [1, 2, 3, 4]
r = test(7, y)
print(r)
r = test(100)
print(r)
r = test(100)
print(r)
Execution result of 3
[1, 2, 3, 4, 7]
[100]
[100]
Recommended Posts