What do two calls of a function with a list as its default argument print?

Coding
Medium
A Python puzzle about when Python creates a function’s default values.
Published

November 16, 2026

NoteQuestion

A function records trades in a list:

def record(trade, book=[]):
    book.append(trade)
    return book

print(record("buy AAPL"))
print(record("sell MSFT"))

What do the two print lines show, and how do you change the function so that each call that leaves out book starts with a new empty list?

Try it first, then open the solution.

The two lines show ['buy AAPL'] and then ['buy AAPL', 'sell MSFT']. Python creates a default value once, when it runs the def line, so every call that leaves out book appends to the same list:

Call book before the call book after the call
record("buy AAPL") [] ['buy AAPL']
record("sell MSFT") ['buy AAPL'] ['buy AAPL', 'sell MSFT']

The fix uses None as the default. When book is None, the function creates a new list:

def record(trade, book=None):
    if book is None:
        book = []
    book.append(trade)
    return book

print(record("buy AAPL"))
print(record("sell MSFT"))

With this version, the two lines show ['buy AAPL'] and ['sell MSFT'].

Two wrong answers are common:

Answer The slip
['buy AAPL'], then ['sell MSFT'] assumes Python creates the default list again at each call
['buy AAPL', 'sell MSFT'], twice forgets that the first print runs before the second call adds its trade
def record(trade, book=[]):
    book.append(trade)
    return book


def record_fixed(trade, book=None):
    if book is None:
        book = []
    book.append(trade)
    return book


print(record("buy AAPL"))
print(record("sell MSFT"))
print(record_fixed("buy AAPL"))
print(record_fixed("sell MSFT"))
['buy AAPL']
['buy AAPL', 'sell MSFT']
['buy AAPL']
['sell MSFT']