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?
["B","D"]
Step-by-Step Solution
Insight: Each call to the outer function creates a completely independent closure with its own isolated cell objects for enclosed variables.
Exam route: f1 and f2 are created by separate calls to outer(), so they have separate x lists. f1(10) -> [10], f1(20) -> [10, 20] (Line Q). f2(30) -> [30] (Line R). f1(40) -> [10, 20, 40] (Line S).
Learning route: This is a closure instance isolation question, recognizable by the nested function returning an inner function that modifies an enclosed mutable variable.
Step 1: When f1 = outer() is executed, a new list x is created in outer's local scope. The inner function captures this specific list in its closure cell. f1 now points to this specific inner function instance.
Step 2: When f2 = outer() is executed, a completely new list x is created. A new inner function instance is created, capturing this new list. f2 points to this second instance. f1 and f2 do not share any state.
Step 3: Line P: f1(10) appends 10 to f1's list. Returns [10].
Step 4: Line Q: f1(20) appends 20 to f1's list. Returns [10, 20]. Option B is correct.
Step 5: Line R: f2(30) appends 30 to f2's list. Since f2's list is independent and starts empty, it returns [30]. Option C is incorrect.
Step 6: Line S: f1(40) appends 40 to f1's list. Returns [10, 20, 40]. Option D is correct.
Answer: Options B and D.