Programming Languages

Python Mutable Defaults: Why a List Can Remember an Earlier Call

SoftwareJobs.io editorial29 November 20262 min read

A Python function with a list as its default argument can behave as though it remembers a previous call. The list is not recreated automatically for every call. The default expression is evaluated when the function is defined.

Predict the output first

def collect(item, items=[]):
    items.append(item)
    return items

print(collect("A"))
print(collect("B"))

The first printed result is ['A']. The second is ['A', 'B'] because both calls use the same default list. The official Python tutorial explains this behaviour for mutable defaults such as lists and dictionaries.

Create a new list when that is the intention

def collect(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Now separate calls without an items argument receive separate lists. If a caller supplies a list, this version still appends to that caller-supplied list. Decide whether that mutation is part of the function’s intended contract rather than assuming the None pattern removes every side effect.

A small practice exercise

  • Run two calls without an explicit list.
  • Run two calls using the same explicit list.
  • Explain which object is being changed each time.

Connect it to real work

In a data or backend interview, explain the expected lifetime of the collection. Shared state can be intentional, but it should be a clear choice. This example helps you spot an accidental shared object before it becomes a confusing test failure.

Sources and further reading

Explore current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter