Fix a shared default list
Call the function twice without passing tags. The second result unexpectedly contains the first tag.
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
Default argument expressions are evaluated once when the function is defined, not once per call.
Why does add_tag("second") return both tags?
Both calls mutate the same default list object.
append mutates the list it is given; it does not copy values from other lists.
The shared object comes from the default argument, not global scope.
The list is mutable; the strings stored in it are not changed.
Why it matters: Mutable default arguments are created once, so they can retain state between calls.