Mutable Default Argument

noun

say it: “MYOO-tuh-bul dih-FAWLT AR-gyuh-ment” /ˈmjutəbəl dɪˈfɔlt ˈɑːrɡjəmənt/

A changeable default value, such as [] in def add(item, cart=[]), which Python makes only once, so every call shares it; the fix is a default of None and a new list inside.

Why is a mutable default argument a problem?

A default like [] is made only once, when the function is defined, so every call shares the same list. Use None as the default and make a new list inside.

def add_item(item, cart=None):
    if cart is None:
        cart = []          # a fresh cart each call
    cart.append(item)
    return cart

print(add_item("pen"))   # ['pen']
print(add_item("book"))  # ['book'], not ['pen', 'book']

In a sentence

  • “Ruff warns about a mutable default argument and suggests None instead.”
  • “The mutable default argument made the second customer's cart start with the first customer's pen.”

Level: Freelancer · More Python terms at this level

Updated