Mutable Default Argument
Multiple Choice Medium
Question
Why is def f(x=[]) dangerous?
Hint
Default args are evaluated once at definition time.
Explanation
In Python, default argument values are evaluated once when the function is defined, not each time it is called. So def f(x=[]) creates one list shared by all calls that use the default. Modifying it persists across calls. The fix is to use None as the default and create the list inside: def f(x=None): if x is None: x = [].
Related Resources
Related Lessons
- Functions
Learn Python functions.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.