ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
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)- A. [2, 2, 2] [2, 2, 2]
- B. [0, 1, 2] [0, 1, 2]
- C. [2, 2, 2] [0, 1, 2]
- D. [0, 1, 2] [2, 2, 2]
Correct answer: D. [0, 1, 2] [2, 2, 2]
With lazy consumption each lambda is called before the generator advances i, so it reads 0, 1, 2. list(gen()) runs the loop to completion first; all lambdas then read the final i = 2.
More Python Programming questions
- What is printed? python x = 1 g = (x y for y in range(3)) x = 2 print(list(g))
- What is printed? python xs = [1, 2, 3] g = (a 10 + b for a in xs for b in xs) xs = [10, 20] print(sum(g))
- What is printed? python def g(): yield 1 yield 2 it = g() for v in it: print(v, end=" ") break for v in it: print(v, end=" ")…
- What is printed? python def g(): total = 0 while True: x = yield total if x is None: return total 100 total += x it = g() next(it)…
- What is printed? python def inner(): a = yield "x" b = yield "y" return (a, b) def outer(): r = yield from inner() yield r o = outer()…
- What is printed? python def g(): try: yield 1 yield 2 except KeyError: yield "caught" yield 3 it = g() print(next(it), it.throw(KeyError)…