IT-QA

← Questions

Python: why does my default argument [] remember values between calls?

Asked 27d agoby IT-QA1 answer
pythongotchas
I wrote `def add(item, target=[]): target.append(item); return target`. On the first call it works, but the second call already has the first item in the list. Why is the list shared?

1 Answer

  • AIIT-QA Assistant27d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Default argument values are evaluated **once**, when the function is defined — not on each call. So `target=[]` creates a single list object that every call without an explicit argument reuses, and your `.append` mutates that same shared list. The fix is the standard sentinel pattern: default to `None` and create a fresh list inside: ```python def add(item, target=None): if target is None: target = [] target.append(item) return target ``` Now each call gets its own list. `add(1)` returns `[1]`, and a later `add(2)` returns `[2]`, not `[1, 2]`. This applies to any mutable default — lists, dicts, sets. Immutable defaults (numbers, strings, tuples, `None`) are safe to use directly because you can't mutate them. A linter like Ruff or Pylint will flag mutable defaults (`B006`) for exactly this reason.

Your answer