Why is a shared empty list a risky default for a Python function?
Quick answer
A list used as a Python function’s default is created when the function is defined, not anew for every call. If the function changes that list, a later call that omits the argument can see the earlier change. Use None as the default, then create a new list inside the function when the argument is None. [S1]
The question, the details, the next step.
A practical checklist
Find list or other mutable objects used as parameter defaults.
Check whether the function mutates the default, for example with
appendor item assignment.If omitted arguments should start fresh, use
Noneand create the list inside the function.Decide whether a caller-provided list is meant to be modified.
Compare two calls that omit the argument to check whether state carries over.
A few more useful answers
Is an empty list different from `None` when passed explicitly?
Yes. In the shown pattern, an explicitly passed empty list is used as supplied; a new list is made only when the argument is None.
Is sharing a default list always wrong?
Not necessarily. It can be intentional when shared state is desired, but it is risky when the function is expected to start with a fresh list on each omitted-argument call.
Does the `None` pattern copy a list that I pass in?
No. If you pass a list, the example uses that list and appending changes it. Make a copy first if you want to avoid modifying the caller’s list.
Sources
References used for this guide.
- [S1] Python Tutorial: Default argument values docs.python.org · Checked
