Python core · Write code
The default list that remembers
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- When exactly is
[]created? Where can you see it? - Why is
cdifferent? - What happens if you write
tags: list = []in a dataclass? And in a Pydantic model? - Is this behaviour ever useful on purpose?
The answer
What a strong answer covers
- Prints
['urgent', 'billing'] ['urgent', 'billing'] ['vip']and thenTrue. - Default values are evaluated once, when
defruns, and stored on the function (add_tag.__defaults__). Every call withouttagsgets the same list. cpasses its own new list, so it isn't shared.- Fix:
tags=None, thenif 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); usefield(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.cachesays 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 voicePractise 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.