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 • 311 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 • 151 views
When would you use a list, tuple, set, or dictionary in Python?
Easy level • 3 views
Explain the difference between Python's GIL (Global Interpreter Lock) and multi-threading vs multi-processing.
Advanced level • 2 views
What is RAII (Resource Acquisition Is Initialization) in C++ and how do smart pointers (unique_ptr, shared_ptr, weak_ptr) prevent memory leaks?
Intermediate level • 2 views