Back
+10 XP
Concept

The Mutable Default Argument Trap

Default arguments are evaluated ONCE at function definition. Using a mutable list `items=[]` causes every call to share the exact same list in RAM.

python
# THE BUG:
def add_bad(val, bag=[]):
    bag.append(val)
    return bag
print(add_bad(1))  # [1]
print(add_bad(2))  # [1, 2] (Shared state bug!)

# THE FIX:
def add_good(val, bag=None):
    if bag is None:
        bag = []
    bag.append(val)
    return bag

# 92. The Mutable Default Argument Trap Default arguments are evaluated ONCE at function definition. Using a mutable list `items=[]` causes every call to share the exact same list in RAM: ```python # THE BUG: def add_bad(val, bag=[]): bag.append(val) return bag print(add_bad(1)) # [1] print(add_bad(2)) # [1, 2] (Shared state bug!) # THE FIX: def add_good(val, bag=None): if bag is None: bag = [] bag.append(val) return bag ``` This is the most famous gotcha in Python technical interviews. Always default mutable arguments (lists, dicts, sets) to `None`, then initialize them inside the function body.

Checkpoint

Why is `def log(item, history=[]):` a notorious Python bug?

Practice

Write a safe function `append_num(n, target=None)` that creates a new empty list if `target is None`, appends `n`, and returns `target`. Print `append_num(5)`.

Terminal
01
Tap code blocks below to assemble
Available Blocks