Back to questions
JuniorTheoryCommon
What does the program print?
def add_item(item, box=[]):
box.append(item)
return box
add_item(1)
print(add_item(2))[1, 2]
- Expecting
[2], as if each call got a fresh empty list: the default[]is created once, whendefruns, so both calls append to the same list. - Expecting a
TypeError, as if a list could not be a default: any object can be one, and the trap is that this one list is shared by every call.
- How would you rewrite
add_itemwith aNonedefault so that each call starts from an empty list? - What does
add_item(3, [])return after these two calls?