datarekha
Python Easy Asked at GoogleAsked at AmazonAsked at Meta

What is the mutable default argument trap in Python, and how do you fix it?

The short answer

Default argument values are evaluated once when the function is defined, not each time it is called. If the default is a mutable object like a list or dict, all calls that use the default share the same object — so mutations in one call persist into the next. The fix is to use None as the default and create the mutable object inside the function body.

How to think about it

This is one of Python’s most reliable interview questions precisely because the bug is invisible until you know where to look. The question is testing whether you understand when default values are created — at definition time, not call time.

Think of it this way: the def statement itself is an executable statement. When Python runs it, it evaluates all the default expressions once and stores them in function.__defaults__. That [] you write in the signature is not a template — it is one actual list object that lives for the lifetime of the function.

See the bug running

Why None works as a sentinel

None is immutable, so it can never accumulate state. Inside the body, if container is None: container = [] creates a brand-new list on every call that omits the argument. The caller who passes an explicit list still gets exactly what they passed — the pattern is backward compatible.

The same trap with dicts and sets

# Broken — shared dict across calls
def register(name, registry={}):
    registry[name] = True
    return registry

# Fixed
def register(name, registry=None):
    if registry is None:
        registry = {}
    registry[name] = True
    return registry

When you actually want the mutable default

Intentional caching (manual memoisation) deliberately exploits this behaviour:

def fib(n, _cache={0: 0, 1: 1}):
    if n not in _cache:
        _cache[n] = fib(n - 1) + fib(n - 2)
    return _cache[n]

This is a known pattern, but functools.lru_cache is cleaner and preferred.

Learn it properly Variables & Types

Keep practising

All Python questions

Explore further

Skip to content