Verified Jobs Live
Python Programming Easy Level ~3 min read

Why is a mutable default argument dangerous, and how can you fix it?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

Default argument expressions are evaluated when the function is defined, not each time it is called. A list used as a default can therefore retain items between calls that omit the argument. Use None as a sentinel and allocate a new list inside the function. If the caller supplies a list, decide whether the function intentionally mutates it or should copy it first. The example intentionally appends to a supplied list while creating a fresh one for omitted arguments.