Why are mutable default arguments risky in Python?medium

Type
conceptual
Topic
mutable-default-arguments
Frequency
common
Tags
functions, defaults, mutability
Answer

Default arguments are evaluated once at function definition time, not on each call. A default like items=[] creates one list shared across all calls, so mutations persist between invocations.

Explanation

Each call that mutates the default leaves the list in a different state for the next call. The fix: use None as the default sentinel and create a fresh list inside the function body. This pattern also explains why dataclasses use field(default_factory=list) rather than a direct list literal — both solve the same underlying problem.

Follow-upHow would you safely default a list argument?
Follow-upDoes the same problem apply to dicts and sets?