Question:medium

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?

Show Hint

Remember that each call to outer() creates a brand new local list; f1 and f2 do not share state, but repeated calls to the same function do.
Updated On: Jul 22, 2026
  • f1 and f2 share the same list x
  • Output of Line Q is [10, 20]
  • Output of Line R is [10, 20, 30]
  • Output of Line S is [10, 20, 40]
Show Solution

The Correct Option is B, D

Solution and Explanation

Step 1: Recall the closure rule.
A Python closure remembers the variables from its enclosing scope by reference, not by value, and a fresh copy of that scope is created on every call to the outer function. Since outer() is called twice, two independent scopes exist, each with its own x.

Step 2: Track state changes call by call.
f1 controls list $x_1$, which starts as [ ]. f2 controls list $x_2$, which starts as [ ] and is totally separate from $x_1$.
Call f1(10): acts on $x_1$, which goes from [ ] to [10]. Printed: [10].
Call f1(20): acts on $x_1$ again, which goes from [10] to [10, 20]. Printed: [10, 20].
Call f2(30): acts on $x_2$, which goes from [ ] to [30]. Printed: [30].
Call f1(40): acts on $x_1$ again, which goes from [10, 20] to [10, 20, 40]. Printed: [10, 20, 40].

Step 3: Match this to the options.
(A) is false because $x_1$ and $x_2$ never mix.
(B) matches the trace exactly ([10, 20] for Line Q), so it is true.
(C) does not match the trace (Line R gives [30], not [10, 20, 30]), so it is false.
(D) matches the trace exactly ([10, 20, 40] for Line S), so it is true.

Step 4: Why this happens under the hood.
Every call to outer() executes its body fresh, which means a new x = [] object is created and a new inner function object is built that closes over that specific x, not over any shared global slot. f1 and f2 hold references to two different inner function objects, each carrying its own closure cell pointing at its own list, so calling f1 repeatedly keeps mutating x1 while f2 keeps mutating a totally separate x2.

Final Answer:
The correct options are (B) and (D). \[ \boxed{\text{(B), (D)}} \]
Was this answer helpful?
0