Mutable Default Arguments - Why they surprise you
This example shows why using a mutable object as a default argument causes shared state across calls. We include a step-by-step trace table and a production-safe fix.
def append_to(element, target=[]):
target.append(element)
return target
print(append_to(1))
print(append_to(2))Trace walkthrough
- At function definition time, Python creates the default list object: list_ref_1 = []
- First call: append_to(1) uses target = list_ref_1, appends 1, returns [1]
- Second call: append_to(2) again uses target = list_ref_1 (same object), appends 2, returns [1,2]
Correct pattern
def append_to(element, target=None):
if target is None:
target = []
target.append(element)
return targetUse `None` as the default and create the mutable inside the function to avoid accidental shared state. This is the recommended production pattern.
Companion video:
Return to Practice Mutable Default Arguments in Python - concise explainer
Timestamps: 00:00 Problem statement · 01:10 Demonstration · 02:40 Fix patterns