This guide explains mutable default arguments: how to avoid common bugs through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
Mutable default objects are shared between calls because the default is created once when the function is defined. Use None as the default and construct a new list inside the function when independent calls are required.
When and Why to Use It
The following example focuses on a practical use of Mutable Default Arguments: How to Avoid Common Bugs.
Step-by-Step Example
def add_task(task_name, tasks=None):
if tasks is None:
tasks = []
tasks.append(task_name)
return tasks
print(add_task("Review"))
print(add_task("Publish"))
Understanding the Example
Both calls without an explicit list return different one-element lists. A default of [] would reuse the same list across calls, accumulating surprising old tasks.
Expected Output
['Review']
['Publish']
Important Behavior and Edge Cases
Passing an existing list explicitly still mutates that caller-owned list. Copy it first if the function should avoid that side effect.
Try It Yourself
Write a function that appends a message to an optional list without sharing a default list.
Common Beginner Mistakes
- Passing an existing list explicitly still mutates that caller-owned list. Copy it first if the function should avoid that side effect.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- Mutable default objects are shared between calls because the default is created once when the function is defined.
- Both calls without an explicit list return different one-element lists.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.