GATE DA 2026 · Programming in Python

MCQ · 1 mark · Problem PROG-PYBS-0007

Consider the given Python program. def append_to_lst(val, lst=[]):
       lst.append(val)
       return lst
print(append_to_lst(1))
print(append_to_lst(2))
print(append_to_lst(3, [])) Which of the following is the correct output of this program?
  1. A
    \[\begin{array}{l}{[1]} \ {[2]} \ {[3]}\end{array}\]
  2. B
    \[\begin{array}{l}{[1]} \ {[1,2]} \ {[3]}\end{array}\]
  3. C
    \[\begin{array}{l}{[1]} \ {[2]} \ {[1,2,3]}\end{array}\]
  4. D
    \[\begin{array}{l}{[1]} \ {[1,2]} \ {[1,3]}\end{array}\]

Solve it on GATE DA practice →More Python Programming problems

Show the worked solutionPython's mutable default argument gotcha: a default argument value (like \(\text{lst=[]}\)) is created once, when the function is defined, and is reused across all calls that don't explicitly supply their own argument for it — it does not get reset to a fresh empty list on each call.• \(\text{append\_to\_lst(1)}\): no list passed, so it uses (and mutates) the shared default list: becomes \([1]\), printed as \([1]\).• \(\text{append\_to\_lst(2)}\): again no list passed, so it reuses the same shared default list (still containing \(1\) from before), appending \(2\): becomes \([1,2]\), printed as \([1,2]\).• \(\text{append\_to\_lst(3, [])}\): this call explicitly passes a brand-new, separate empty list, so it's unaffected by the shared default: becomes \([3]\), printed as \([3]\).Answer: [1], [1,2], [3]Click Here for Detail SolutionGateOverflow discussion: https://gateoverflow.in/523209/gate-da-2026-question-6

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com