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 • 391 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 • 233 views
Explain the difference between Python's GIL (Global Interpreter Lock) and multi-threading vs multi-processing.
Advanced level • 92 views
Explain the SOLID principles in Object-Oriented Software Design with concise engineering examples.
Intermediate level • 90 views
When should Python code use threads, processes, or asyncio?
Medium level • 90 views