ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
fs = []
for i in range(3):
fs.append(lambda x: x + i)
i = 10
print([f(1) for f in fs])- A. [11, 11, 11]
- B. [1, 2, 3]
- C. [3, 3, 3]
- D. [13, 13, 13]
Correct answer: A. [11, 11, 11]
Each lambda looks up the global i when CALLED, not when created. After the loop, i is rebound to 10, so every call returns 1 + 10 = 11.
More Python Programming questions
- What is printed? python def make(): fs = [] for i in range(3): fs.append(lambda: i) i = "z" return fs print([f() for f in make()])
- 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)