Mutable default arguments in Python: what is the bug?

Django Interview Q&A November 13, 2026 python

What is the bug with mutable default arguments in Python, and how do you fix it?

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ======================================================================
# Q: What is the bug with mutable default arguments in Python, and how do you
# fix it?
# ======================================================================

def add(item, bucket=[]):   # WRONG: the list is created once
    bucket.append(item); return bucket

def add(item, bucket=None):  # CORRECT
    bucket = [] if bucket is None else bucket
    bucket.append(item); return bucket