Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

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

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]

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away