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.
TipSolution
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 isNone: book = [] book.append(trade)return bookprint(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
NoteCode: a list as a default argument
def record(trade, book=[]): book.append(trade)return bookdef record_fixed(trade, book=None):if book isNone: book = [] book.append(trade)return bookprint(record("buy AAPL"))print(record("sell MSFT"))print(record_fixed("buy AAPL"))print(record_fixed("sell MSFT"))