[Python] Default mutable arguments (like []) are evaluated once when the function is defined, not every time it's called.

Default mutable arguments (like []) are evaluated once when the function is defined

While preparing a MCQ section in a coding test, I encountered some patterns with default mutable arguments


Example

def append_twice(val, lst=[]):
    lst.append(val)
    lst.append(val)
    return lst

print(append_twice(1))  # [1, 1]
print(append_twice(2))  # [1, 1, 2, 2] ← shared list

Why Is lst Shared?

Because in both calls, nothing was passed as the second argument — so Python uses the default, which is [].

And in Python:

❗ Default mutable arguments (like []) are evaluated once when the function is defined, not every time it's called.

How to avoid it:

Always use None as the default for mutable arguments:

def append_twice(val, lst=None):
    if lst is None:
        lst = []
    lst.append(val)
    lst.append(val)
    return lst

append_twice(1) # [1, 1]  
append_twice(2) # [2, 2]

Comments