L2 · Working engineerPython internals~3 min · 4 tests#66

Fix the Mutable Default Argument Bug

Find and fix Python's mutable default argument bug where def f(items=[]) shares one list across calls. Use the None sentinel pattern. Tested live.

The problem

This function has a famous bug:

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

add_item(1)   # [1]
add_item(2)   # [1, 2]  ← the same list again!

Fix add_item so every call without an items argument starts from a fresh empty list, while a list you pass in is still appended to.

Examples

  1. Example 1

    Input

    (add_item(1), add_item(2))

    Expected output

    ([1], [2])
  2. Example 2

    Input

    add_item(3, [0])

    Expected output

    [0, 3]

+ 2 hidden tests on Submit — still appends to a passed list.

Edge cases to ask about

  • Repeated calls with the default
  • Caller passes their own list

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · add_item
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    None sentinelO(1)O(1)Create the default inside the function body.
    Walkthrough of the optimal approach (try it yourself first)

    Default argument values are evaluated once, when the function is defined, not on each call. So items=[] is a single list object shared by every call that relies on the default.

    The fix is the None sentinel: items=None, then if items is None: items = [] inside the body. The same trap applies to {}, set() and any mutable default.

    Complexity: O(1) time, O(1) space. One append per call.

    Reveal the reference solution
    def add_item(item, items=None):
        if items is None:
            items = []
        items.append(item)
        return items

    Follow-ups interviewers ask

    • Is there ever a legitimate use for a mutable default? (caches)
    • Inspect add_item.defaults.

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Fix the Mutable Default Argument Bug in Python?

    The optimal solution runs in O(1) time and O(1) auxiliary space. One append per call.

    What follow-up questions do interviewers ask about Fix the Mutable Default Argument Bug?

    Is there ever a legitimate use for a mutable default? (caches) Inspect add_item.__defaults__.