Question:

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
collegedunia
Verified By Collegedunia

The Correct Option is B, D

Solution and Explanation

Step 1: Understand what outer() creates.
Each time outer() is called, Python creates a brand new local variable x = [] and a brand new inner function that closes over that particular x. The inner function does not share x with any other call to outer(); each call gets its own private list captured in the closure.

Step 2: Trace f1 = outer() and f2 = outer().
f1 = outer() creates one x (call it x1 = []) and binds f1 to the inner function that appends to x1.
f2 = outer() creates a completely separate x (call it x2 = []) and binds f2 to the inner function that appends to x2.
So f1 and f2 never touch the same list, they each keep growing their own list across repeated calls.

Step 3: Trace each print statement.
Line P: f1(10) appends 10 to x1, so x1 = [10]. Output: [10].
Line Q: f1(20) appends 20 to the same x1 (because f1 remembers x1 between calls), so x1 = [10, 20]. Output: [10, 20].
Line R: f2(30) appends 30 to x2, which is still empty at this point since f2 was never called before, so x2 = [30]. Output: [30].
Line S: f1(40) appends 40 to x1 again, so x1 = [10, 20, 40]. Output: [10, 20, 40].

Step 4: Check each option.
(A) claims f1 and f2 share the same list x. From Step 2 this is false, they have separate lists.
(B) claims Line Q prints [10, 20]. This matches the trace exactly, so it is true.
(C) claims Line R prints [10, 20, 30]. The trace shows Line R prints [30] only, so this is false.
(D) claims Line S prints [10, 20, 40]. This matches the trace, so it is true.

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

Top GATE DA Data Science and Artificial Intelligence Questions

View More Questions

Top GATE DA Programming in Python Questions

View More Questions