Python Developer interview question
Why are mutable default arguments dangerous?
Default arguments are evaluated once when a function is defined, so a mutable list or dict is shared across calls; use None and create a fresh object inside instead.
Direct answer
What a strong answer covers
How it works
Default values are expressions evaluated exactly once, when the def statement runs, and stored on the function object. A list, dict, or set default is therefore one object that every call without that argument shares, so mutations from one call leak into the next. The idiom is a None sentinel with the real default created inside the body. The same evaluation rule also explains why a default of datetime.now() is frozen at import time.
Example
def add_item(item, items=[]) appends to the same list on every call, so add_item(1) followed by add_item(2) returns [1, 2] from the second call. Writing items=None and then items = [] if items is None else items gives each call a fresh list and makes the intent explicit.
Common mistakes
- Only noticing the bug in tests that run in a different order than production.
- Fixing it with items.copy() inside the function while still sharing the default.
- Assuming the problem is limited to lists when any mutable default, including a class instance, behaves the same.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.