The mutable default trap

This is one of the most asked Python interview questions. What does this print?

def add(item, items=[]):
    items.append(item)
    return items

add(1)
add(2)  # [1, 2], not [2]

The default list is created once, when the def runs, and every call that leaves out items shares that same list. Each call appends to it, so the list keeps growing between calls.

The fix: default to None, and make a new list inside the function.

def add(item, items=None):
    if items is None:
        items = []

The same applies to dicts and sets. Any mutable default is a bug waiting to happen. Linters flag it, and the Debugging challenges have one like it.

Run it, then call add_fixed a few more times to see each call start fresh.