Skip to main content

Functions the Pythonic Way

Default Arguments Done Right

0:00
LearnStep 1/3

The Mutable Default Argument Trap

One of the most common pitfalls for new Python developers is using mutable objects (like lists or dictionaries) as default argument values.

The Evaluation Rule

In Python, default argument values are evaluated only once, when the function is defined (def statement is executed). They are not re-evaluated each time the function is called.

The Trap

If you use a mutable object as a default, that single object instance is shared across all calls that omit that argument.

python

The box list persists between calls, accumulating items unexpectedly.

The Solution: None as a Sentinel

The standard, idiomatic way to handle this is to use None as the default value and create the mutable object inside the function.

python

This pattern ensures that a new container is initialized for every function call where the argument is skipped, keeping your functions pure and predictable.