Why Does a Python Default List Argument Keep Its Old Values?

Asked 1 hour ago 10 views

0

I ran into a Python behavior that surprised me: calling a function more than once seems to add to the same list, even though I expected a fresh one each time.

def add_name(name, names=[]):
    # This default list is created once when Python defines the function.
    names.append(name)
    return names

print(add_name("Maya"))
print(add_name("Leo"))

Both calls return a list containing both names. Is this simply how a mutable default argument works, or is there a case where reusing that object is intentional? I’m also curious what the clearest alternative is when a function should start with a new list on every call.

0 Answers


Write Your Answer