Skip to the page

Python core · Write code

The default list that remembers

The interviewer asks

What does this print, and why? How would you fix the function?

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

a = add_tag("urgent")
b = add_tag("billing")
c = add_tag("vip", [])
print(a, b, c)
print(a is b)

Then

Follow-ups the interviewer asks next

  1. When exactly is [] created? Where can you see it?
  2. Why is c different?
  3. What happens if you write tags: list = [] in a dataclass? And in a Pydantic model?
  4. Is this behaviour ever useful on purpose?

The answer

What a strong answer covers

  • Prints ['urgent', 'billing'] ['urgent', 'billing'] ['vip'] and then True.
  • Default values are evaluated once, when def runs, and stored on the function (add_tag.__defaults__). Every call without tags gets the same list.
  • c passes its own new list, so it isn't shared.
  • Fix: tags=None, then if tags is None: tags = [] inside. The same goes for dict and set defaults.
  • A dataclass refuses it (ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory); use field(default_factory=list). Pydantic copies a mutable default for each instance.
  • Linters catch it (Ruff and flake8-bugbear rule B006).
  • On purpose: a crude per-process memo cache, but functools.cache says it more clearly.

The red pen

Common traps

Avoid:saying the output is ['urgent'] ['billing'] ['vip']; "fixing" it with tags=list() (still evaluated once).

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview