1. Home
  2. Interview Questions
  3. Python
  4. Why does using a mutable default argument like a list cause …

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: Default argument values are evaluated once, when the def statement runs, not on every call. A mutable default such as a list or dict is therefore shared across all calls, so changes made in one call leak into later calls. The standard fix is to default to None and create a new object inside the function.

Detailed explanation

In Python, def is an executable statement. When the interpreter runs it, it builds a function object and evaluates every default expression right then. The resulting values are stored on the function object. Positional defaults go in func.__defaults__. Keyword-only defaults go in func.__kwdefaults__.

On each call where the caller does not supply that argument, Python binds the parameter name to the same stored object. It does not make a copy. This has different effects depending on the type:

  • Immutable defaults (int, str, tuple, None, frozenset) are safe. Code that seems to change them really rebinds the local name to a new object.
  • Mutable defaults (list, dict, set, custom objects) are risky. Methods like append, update or add change the shared object in place. That change is still there on the next call.

The same once-only evaluation applies to any expression, not just mutable literals. For example, def log(msg, ts=datetime.now()) records the time the module was imported, not the time of each call.

The idiomatic fix is the None sentinel: use None as the default and build a new object inside the body. If None is itself a valid value callers might pass, use a private sentinel instead, such as _MISSING = object(), and compare with is.

Sometimes a shared mutable default is used on purpose, for example as a simple per-function cache. This works, but it is hidden state. functools.lru_cache or an explicit module-level dict is clearer. Note that dataclasses refuse a list, dict or set default and raise ValueError. You must use field(default_factory=list) there.

Example

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

print(add_item('a'))   # ['a']
print(add_item('b'))   # ['a', 'b']  same list reused
print(add_item.__defaults__)  # (['a', 'b'],)

# Correct version
def add_item(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(add_item('a'))   # ['a']
print(add_item('b'))   # ['b']

# When None is a meaningful value, use a private sentinel
_MISSING = object()

def get_setting(key, default=_MISSING):
    if key in settings:
        return settings[key]
    if default is _MISSING:
        raise KeyError(key)
    return default   # caller may legitimately pass None

# Dataclasses need default_factory
from dataclasses import dataclass, field

@dataclass
class Cart:
    items: list = field(default_factory=list)

Printing __defaults__ shows the problem directly. The list is attached to the function object and keeps growing across calls.

Common mistakes

  • Writing bucket = bucket or [] or if not bucket:. This also replaces an empty list the caller passed in on purpose. The caller then never sees the items appended to their list. Always test with is None.
  • Believing Python creates a fresh default on each call. Interviewers want to hear that defaults are evaluated once, at function definition time.
  • Thinking only lists are affected. Dicts, sets, class instances and expressions like datetime.now() or uuid4() show the same once-only behaviour.
  • Fixing it by copying the default inside the function, for example bucket = list(bucket). This hides the symptom but makes intent unclear. The None pattern is the accepted convention, and linters such as flake8-bugbear (B006) flag mutable defaults.

Follow-up questions

  • Where exactly are default values stored on a function object, and how would you inspect them?
  • How would you handle a parameter where None is a legitimate value the caller can pass?
  • Why does a dataclass raise an error for a list default, and what does default_factory do?

Interview tip: Show the buggy output first, then say "defaults are evaluated once at def time and stored in __defaults__". That one sentence proves you understand the cause, not just the fix.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More medium Python questions

All medium questions →

Related Questions

‹
Q6 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA