KITFORMA · EDITORIAL ANSWER
Why does a Python function remember items from the previous call?
KitForma editorial guide. A mutable default argument is created when the function is defined, not each time it runs. A default list can therefore become accidental shared state.
Step-by-step answer
def collect(item, bucket=None): and create bucket = [] only when bucket is None; then append and return it. Call the function twice without a bucket and confirm the returned lists are different objects. Also pass an explicit empty list and verify that it is reused intentionally. Do not use bucket = bucket or []: that silently replaces a caller’s empty list. A deliberately shared cache needs a separate documented lifetime and concurrency policy.
Minimal example:
def collect(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
a, b = collect("a"), collect("b")
assert a == ["a"] and b == ["b"] and a is not b
owned = []
assert collect("x", owned) is ownedSources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.