def add(item, box=[]): box.append(item); return box. What does calling add(1) and then add(2) return the second time?
Correct answer
B. [1, 2]
16 views
B. [1, 2]
16 views
Default arguments are evaluated once, when the function is defined, so the same list is reused across calls. The safe pattern is box=None, then create a new list inside the function.
Asked in: NTS, Python Developer Interviews
Not sure why the answer is B? Ask here and get an explanation.