Avoid Shared Mutable Function Defaults
Core idea
A list used as a parameter default is created when the definition executes. Calls that omit that argument share the same list. To create a separate list for each omitted argument, default to None and create the list inside the body. Here None is a sentinel, a special marker for a missing list.
def record(label, labels=[]): labels.append(label) return labels
print(record("A"))print(record("B"))The second call sees the list modified by the first call.
Create a fresh default list
def record(label, labels=None): if labels is None: labels = [] labels.append(label) return labels
print(record("A"))print(record("B"))Each omitted argument leads to a new list.
Preserve an explicit empty list
def record(label, labels=None): if labels is None: labels = [] labels.append(label) return labels
items = []record("C", items)print(items)An explicitly supplied list is mutated by this contract, even if it starts empty.
Common mistake
if not labels would also replace an explicitly supplied empty list. Use is None when only None should request a fresh list. If None is itself a valid distinct input, a different sentinel is needed.
Practice
Write a function adding a reading to an optional list. Call it twice without the list, then with an explicit empty list. Verify the three results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mutable defaults
Check your understanding of mutable defaults.
What is printed?
def add(n, items=[]): items.append(n) return itemsadd(1)print(add(2))What is printed?
def add(n, items=None): if items is None: items = [] items.append(n) return itemsadd(1)print(add(2))What is printed?
def add(n, items=None): if items is None: items = [] items.append(n)x = []add(3, x)print(x)Why use items is None rather than not items?