0
1

More than 3 years have passed since last update.

関数のデフォルト引数でリストを与えてしまうと・・・

Last updated at Posted at 2020-01-08
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]
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1