A default argument that remembers — Aptitude Question
A default argument that remembers: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 105 seconds
Question
What does this Python program print?
def add(item, target=[]):
target.append(item)
return target
print(add(1))
print(add(2))Options
- [1] and then [2]
- [1] and then [1, 2]
- [1] and then [1]
- [1, 2] and then [1, 2]
Show the answer and the worked solution
Correct answer: B. [1] and then [1, 2]
Worked solution
- The default [] is evaluated once, when the def statement runs, and stored with the function.
- The first call appends 1 to that stored list and returns it, printing [1].
- The second call receives the very same list, which already holds 1, appends 2 and prints [1, 2], so the two lines are [1] and then [1, 2].
Answer: [1] and then [1, 2].
The idea
Default arguments are evaluated once at definition time, so a mutable default is shared across every call. The standard remedy is target=None with target = [] inside the body.
Shortcut. Each print runs straight after its call, so the first line is [1] and the second must contain 2, which leaves two options; both calls share one stored default list, so it is [1, 2].
Common trap. "[1] and then [2]" assumes a fresh empty list on every call, which is true only for defaults created inside the body.
All Programming Fundamentals questions · placement mock tests