Question:

Consider the following Python code: 

Show Hint

Each function call to outer() creates a new closure with its own independent variable environment.
Updated On: Feb 15, 2026
  • Output of line Q is [10, 20]
  • Output of line S is [10, 20, 40]
  • Output of line R is [10, 20, 30]
  • F1 & F2 share the same list 
     

Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

The question involves understanding closures in Python and how they maintain their own environments.

Let's analyze the provided Python code step-by-step: 

  1. The function outer() is defined, which initializes an empty list x.
  2. Inside outer(), there's an inner function inner(val) that appends val to x and returns x.
  3. outer() returns the inner function.

The code execution proceeds as follows:

  1. F1 = outer() creates a new list x for F1 and assigns the inner function to F1.
  2. F2 = outer() creates another new list x for F2, independent of F1's list.
  3. print(F1(10)): Calls F1's function, which adds 10 to x. The list becomes [10].
  4. print(F1(20)): Calls F1 again, adding 20 to x. The list becomes [10, 20].
  5. print(F2(30)): Calls F2, which is independent, adding 30 to its list. The list for F2 becomes [30].
  6. print(F2(40)): Calls F2 again, adding 40. The list for F2 becomes [30, 40].

Now, let's match this with the given options:

  • Output of line Q is [10, 20]: This is correct since line Q refers to print(F1(20)), which indeed outputs [10, 20].
  • Output of line S is [10, 20, 40]: Incorrect, as line S refers to F2(40), having no connection to the F1 list.
  • Output of line R is [10, 20, 30]: Incorrect, as F1 and F2 have separate lists.
  • F1 & F2 share the same list: Incorrect, they have independent lists.

Based on the above reasoning, the correct answer is:

Output of line Q is [10, 20]

Was this answer helpful?
0
0