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 is/are correct?
Correct Answer :
Output of line Q is [10, 20]
Output of line S is [10, 20, 40]
Solution :
The correct options are:
1. Output of line Q is [10, 20]
2. Output of line S is [10, 20, 40]
Detailed Explanation:
1. Understanding Closures in Python:
When a nested function (like inner) references a variable (like x) from its enclosing scope (like outer), a closure is created. The nested function retains access to the variables defined in its outer scope even after the outer function has finished executing.
2. Independent Closures:
Every time outer() is called, Python creates a new, independent local scope with a brand-new list object x:
- The call f1 = outer() creates a unique list x (let's call it x_f1) and returns an instance of inner associated with x_f1.
- The call f2 = outer() creates a second, completely separate list x (let's call it x_f2) and returns an instance of inner associated with x_f2.
Since each function call creates a new scope, f1 and f2 do not share the same list x.
3. Step-by-Step Code Execution Trace:
- Line P (print(f1(10))): f1 is called with the value 10. This value is appended to x_f1, modifying the list to [10] and printing it.
- Line Q (print(f1(20))): f1 is called with the value 20. This value is appended to x_f1, modifying the list to [10, 20] and printing it. This makes the first correct option true.
- Line R (print(f2(30))): f2 is called with the value 30. Because f2 operates on its own independent empty list x_f2, the value 30 is appended to it, resulting in [30]. (This confirms that the option claiming line R outputs [10, 20, 30] is incorrect.)
- Line S (print(f1(40))): f1 is called with the value 40. The value 40 is appended to x_f1 (which currently holds [10, 20]), modifying the list to [10, 20, 40] and printing it. This makes the second correct option true.
Access expert-curated educational resources and study materials—completely free.
Create, conduct, and manage professional online assessments with Mindyard. Perfect for teachers and institutes.
Copyright © 2026 Mindyard. All Rights Reserved.