Repository navigation
tricky question #7
|
You’re building a small shop app. A teammate wrote this function so that each customer gets a bag they can add items to. It seems harmless, but the app keeps showing customers items they never added. python print(add_item(1), add_item(2), add_item(3, [])) a) Predict: What exact output appears on screen? Write all three lists. |
Replies: 1 comment
a) Predicted outputb) Why the first two lists look identicalTwo things combine here:
This is also why customers see items they never added: all bag-less calls share one hidden bag. c) The fixUse def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
first = add_item(1)
second = add_item(2)
print(first) # [1]
print(second) # [2]
print(first is second) # False, they are different listsOutput: Now each call without a |
a) Predicted output
b) Why the first two lists look identical
Two things combine here:
The default value is created once, when
defruns, not on each call. Python evaluatesbucket=[]a single time, when the function is defined, and stores that one list object on the function. Every call that omitsbucketreuses that same list.printevaluates all its arguments before printing anything. The calls happen in order:add_item(1)appends 1 to the shared default list and returns that same list object (not a copy).add_item(2)appends 2 to the same list and returns it again.add_item(3, [])gets a brand new list, so it's unaffected:[3].Only after all three calls finish d…