ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def make():
fs = []
for i in range(3):
fs.append(lambda: i)
i = "z"
return fs
print([f() for f in make()])- A. [2, 2, 2]
- B. ['z', 'z', 'z']
- C. [0, 1, 2]
- D. ['z', 1, 2]
Correct answer: B. ['z', 'z', 'z']
All three lambdas close over the same cell for the local variable i. That cell is reassigned to 'z' before make returns, so every closure reads 'z'.
More Python Programming questions
- What is printed? python from functools import partial def p(a, b): return a 10 + b fs = [partial(p, i) for i in range(3)] gs = [lambda b…
- What is printed? python def counter(): count = 0 def inc(): nonlocal count count += 1 return count def peek(): return count return inc…
- What is printed? python x = 0 def outer(): x = 1 def mid(): def inner(): nonlocal x x += 10 return x return inner() r = mid() return r, x…
- What is printed? python def f(): try: print(y, end=" ") except NameError as e: print(type(e).name, end=" ") y = 1 y = 5 f() print(y)
- What is printed? python def gen(): for i in range(3): yield lambda: i a = [f() for f in gen()] b = [f() for f in list(gen())] print(a, b)
- What is printed? python x = 1 g = (x y for y in range(3)) x = 2 print(list(g))