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.
Saved automatically
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.
Related Questions in Python Programming
Explain Python GIL (Global Interpreter Lock) and how to bypass it for CPU-bound tasks
Advanced level • 315 views
What is the Python Global Interpreter Lock (GIL), how does it impact multi-threaded CPU-bound programs, and what are the workarounds in Python 3.12+?
Intermediate level • 157 views
Explain the difference between Python's GIL (Global Interpreter Lock) and multi-threading vs multi-processing.
Advanced level • 8 views
When would you use a list, tuple, set, or dictionary in Python?
Easy level • 8 views
How does Memory Management and Garbage Collection work internally in Python (CPython)?
Advanced level • 6 views