Skip to content
Preptima
mediumConceptCodingEntryMidSenior

Why does a mutable default argument keep the values from previous calls?

Python mutable default arguments are evaluated once when def runs, so omitted calls share the same list or dict stored in the function's __defaults__. It also connects mutability to the point an interviewer is testing.

3 min readUpdated 2026-08-15

Answer

Short answer

A mutable default persists because Python evaluates default expressions once at function definition time. Use None or a private sentinel, then create a fresh list or dict inside the function for each call that omitted the argument.

Was this answer helpful?

Likely follow-ups

  • When is a mutable default deliberately useful, for instance as a memoisation cache?
  • Why is None a poor sentinel when the caller may legitimately pass None, and what do you use instead?
  • Why does a dataclass raise an error for a list default but accept an arbitrary mutable object?
  • How would you write a decorator that gives each call a fresh copy of the declared default?

Related questions

Further reading