Shared mutable default across function calls
Predict the printed lists and explain why the second call is affected.
Code Snippet
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
a = add_tag("api")
b = add_tag("db")
print(a, b, a is b)Expected Output & Explanation
['api', 'db'] ['api', 'db'] True The default list [] is created once when add_tag is defined. Both calls mutate and return that same list object, so a and b refer to the identical list.
Follow-up Interview Question · How do you write add_tag safely while preserving an optional tags parameter?
Module Context & References
Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown