236 views
0 0 votes

Consider the following Python code:

def outer():
    x = []
    def inner(val):
        x.append(val)
        return x
    return inner

Now consider:

f1 = outer()
f2 = outer()

print(f1(10))  # P
print(f1(20))  # Q
print(f2(30))  # R
print(f1(40))  # S

What will be the output of $\verb|P|$, $\verb|Q|$, $\verb|R|$, and $\verb|S|$?

  1. Output at line $\verb|Q|$ is $[10,20]$.
     
  2. $\verb|f1|$ and $\verb|f2|$ share the same list.
     
  3. Output at line $\verb|S|$ is $[10,20,40]$.
     
  4. Output at line $\verb|R|$ is $[10,20,30]$.

1 Answer

1 1 vote

Answer: (A) Output at line Q is and (C) Output at line S is

When outer() is called, a new local variable x (an empty list) is created each time.

  • f1 and f2 are two separate instances of the inner function, each with its own closure over a distinct x list created by their respective calls to outer().
  • f1(10) appends 10 to f1's list x, so P is [10].
  • f1(20) appends 20 to the same f1 list x, so Q is [10, 20].
  • f2(30) appends 30 to f2's separate list x, so R is [30].
  • f1(40) appends 40 to the same f1 list x, so S is [10, 20, 40].

Based on this, options A and C are correct statements. Option B is incorrect because f1 and f2 have separate lists. Option D is incorrect because R's output is [30].

Answer:
Position:
Show:

Related questions

0 0 votes
2 2 answers
290
290 views
GO Classes asked Feb 17
290 views
A binary tree has the following traversals:Preorder traversal$: P, Q, S, E, R, F, G$ Inorder traversal$: S, Q, E, P, F, R, G$ Which of the following statement(s) is/are T...
1 1 vote
0 0 answers
235
235 views
GO Classes asked Feb 17
235 views
Let $G=(V,E)$ be a directed graph, and let $G^R$ denote the graph obtained by reversing all the edges of $G$.Which of the following statements is/are TRUE?If a vertex $v$...
1 1 vote
2 2 answers
325
325 views
GO Classes asked Feb 17
325 views
Consider the following function:def fun(L, i = 0): if i >= len(L) - 1: return 0 if L[i] L[i + 1]: L[i], L[i + 1] = L[i + 1], L[i] return ...
1 1 vote
3 3 answers
293
293 views
GO Classes asked Feb 17
293 views
Consider the following function:def mystery(n): if n <= 0: return 1 else: return mystery(n - 1) + mystery(n - 2)If the function is called as $\tex...