Mutating against rebinding — Aptitude Question
Mutating against rebinding: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 90 seconds
Question
What does this Python program print?
def f(lst):
lst.append(4)
lst = [9, 9]
lst.append(5)
a = [1, 2, 3]
f(a)
print(a)Options
- [1, 2, 3]
- [1, 2, 3, 4]
- [1, 2, 3, 4, 5]
- [9, 9, 5]
Show the answer and the worked solution
Correct answer: B. [1, 2, 3, 4]
Worked solution
- lst starts out referring to the caller's list, so lst.append(4) makes that list [1, 2, 3, 4].
- lst = [9, 9] rebinds the local name to a brand new list, breaking the link to the caller's object.
- The final append therefore lands on the new list, which is discarded when f returns, so a prints as [1, 2, 3, 4].
Answer: [1, 2, 3, 4].
The idea
Python passes references by value: mutating the object is visible to the caller, rebinding the name is not. The dividing line is the assignment statement in the middle.
Shortcut. Only what happens before lst = [9, 9] reaches the caller, and that is the append(4); everything after it touches a new list.
Common trap. "[1, 2, 3, 4, 5]" misses that the rebinding cuts the link, and so lets the append(5) land on the caller's list too.
All Programming Fundamentals questions · placement mock tests