Pointer Walk

Python's Mutable Default Arguments

A list used as a default argument is built once and shared by every call.

Languages and RuntimesBeginner6 min read

One function, two calls

What does this print?

python
def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("apple"))
print(add_item("pear"))

Most people expect ["apple"] and then ["pear"]. Each call gets an empty basket by default, adds one thing, and returns it.

The second line actually prints ["apple", "pear"].

When is the default created?

The answer hangs on one question: when does Python build that []?

Not when the function is called. It is built once, when the def line runs, and stored with the function. Every call that does not pass a basket gets that same stored list. Not a copy. The same one.

One function, two callsInteractive
1def add_item(item, basket=[]):
2 basket.append(item)
3 return basket
4
5print(add_item("apple"))
6print(add_item("pear"))

What exists in memory

nothing yet

Start. Press play, or step through one line at a time.

  1. The def line runs once

    Python creates the function, and creates the default list alongside it.

  2. The first call uses that list and changes it

    append modifies the list in place.

  3. The function ends. The list does not

    It belongs to the function, not to the call.

  4. The second call receives the same list

    It still contains what the first call put there.

You can see the stored list directly:

python
>>> add_item.__defaults__
(['apple', 'pear'],)

Why only some defaults are a problem

Defaults like count=0 or name="" behave exactly as you would hope. The difference is whether the value can be changed in place.

Default valueCan it be changed in place?Safe as a default?
0, 3.5, TrueNoYes
"text"NoYes
NoneNoYes
(1, 2) (a tuple)NoYes
[] (a list)YesNo
{} (a dict)YesNo
set()YesNo

A number is shared between calls too. But count += 1 does not alter the number 0. It makes count point at a new number. The stored default is untouched. A list is different: append changes the list itself, and everyone holding that list sees the change.

The fix

Use None as the default and build the real value inside the function, where the code runs on every call.

The fix: None as the defaultInteractive
1def add_item(item, basket=None):
2 if basket is None:
3 basket = []
4 basket.append(item)
5 return basket
6
7print(add_item("apple"))
8print(add_item("pear"))

Variables

nothing yet

Start. Press play, or step through one line at a time.

python
def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

This pattern is so standard that experienced Python programmers type it without thinking, and code checkers warn about a list or dict used as a default.

Key takeaways

  • A default argument is created once, when the function is defined, not on each call.
  • Every call that relies on the default shares the same object.
  • That is harmless for values that cannot change, such as numbers, strings and None.
  • It is a bug for lists, dicts and sets, because changes made by one call are seen by the next.
  • Use None as the default and create the list inside the function.

Your progress

Check your progress

0%

  1. Read the page50% of this page

    When you have gone through the page and its animations, tick it off.

  2. Take the quiz50% of this page

    6 questions, from easy to hard. Take it as often as you like: the questions change, and only your best score counts.

Saved on this device only. See all your progress