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)
  1. A. [2, 2, 2] [2, 2, 2]
  2. B. [0, 1, 2] [0, 1, 2]
  3. C. [2, 2, 2] [0, 1, 2]
  4. 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

Exams that ask this topic