LoginSignup
0
2

More than 3 years have passed since last update.

リストや辞書をデフォルト引数にする場合の注意点

Last updated at Posted at 2020-02-29

リストや辞書は参照渡しなので注意

def test_func(x, l=[]):
    l.append(x)
    return l


r = test_func(100)
print(r)

r = test_func(100)
print(r)

デフォルト引数として空のリストにしたはずが・・・

[100]
[100, 100]

改良するには、下記のようにする

def test_func(x, l=None):
    if l is None:
        l = []
    l.append(x)
    return l


r = test_func(100)
print(r)

r = test_func(100)
print(r)

出力:

[100]
[100]

0
2
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
2