1
def test(x, l=[]):
l.append(x)
return l
y = [1, 2, 3, 4]
r = test(7, y)
print(r)
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)
2の実行結果
[100]
[100, 100]
同じ処理を二回したつもりが、
二回目は100が二個になる。
これは、リストが参照渡しであるが為に起こる。
バグに繋がる事が多いため、
リストやデイクショナリーの様に参照渡しのものをデフォルト引数におかない。
そこで以下の様に書く。
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)
3の実行結果
[1, 2, 3, 4, 7]
[100]
[100]