GATE DA 2026 · Programming in Python

MSQ · 2 marks · Problem PROG-PYBS-0009

Consider the given Python program. def outer():
x = []
def inner(val):
    x.append(val)
return x return inner
f1 = outer()
f2 = outer()
print(f1(10)) # Line P
print(f1(20)) # Line Q
print(f2(30)) # Line R
print(f1(40)) # Line S Which of the following options is/are correct?
  1. A
    \({f1}\) and \({f2}\) share the same list \(x\)
  2. B
    Output of Line \(\text{Q}\) is \([10, 20]\)
  3. C
    Output of Line \(\text{R}\) is \([10,20,30]\)
  4. D
    Output of Line \(\text{S}\) is \([10, 20, 40]\)

Solve it on GATE DA practice →More Python Programming problems

Show the worked solutionPython's closures capture variables by reference to the enclosing scope, and crucially, \(x=[]\) here is a statement executed fresh, every time \(\text{outer()}\) is called (unlike a mutable default argument, which is created only once at definition time). So \(f1=\text{outer()}\) and \(f2=\text{outer()}\) each get their own separate, independent list — they do not share the same \(x\).• Line P: \(f1(10)\) appends to \(f1\)'s own list: prints \([10]\).• Line Q: \(f1(20)\) appends to the same list \(f1\) has been using: prints [10, 20].• Line R: \(f2(30)\) appends to \(f2\)'s separate list (still empty until now): prints \([30]\) — not \([10,20,30]\), since \(f2\)'s list is independent of \(f1\)'s.• Line S: \(f1(40)\) appends again to \(f1\)'s (now \([10,20]\)) list: prints [10, 20, 40].Answer: Output of Line Q is [10,20]; and output of Line S is [10,20,40].Click Here for Detail SolutionGateOverflow discussion: https://gateoverflow.in/523175/gate-da-2026-question-40

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