1.What happens when you use a mutable object like a list as a default argument value in a function, and why?
Warm-upWhat a strong answer covers
- Default argument values are evaluated once at function definition time, not on each call, so the same list object is shared across every call that relies on the default
- Mutating that shared default (e.g. appending) causes state to leak between calls, a classic source of surprising bugs
- The idiomatic fix is to default to None and create a fresh list inside the body: def f(x, acc=None): if acc is None: acc = []
- Ties back to Python binding default values to the function object at def time, stored in func.__defaults__
Where people lose the point
- Claiming defaults are re-evaluated on every call, which is the opposite of the real behavior
- Suggesting you should just avoid lists entirely rather than using the None sentinel pattern
- Confusing this with variable scope rather than the timing of default-value evaluation