ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def gen(n):
    for i in range(n):
        yield i * i
g = gen(4)
print(sum(g), sum(g), list(gen(0)))
  1. A. 14 0 [0]
  2. B. 14 0 []
  3. C. 14 14 []
  4. D. 0 0 []

Correct answer: B. 14 0 []

A generator is single-use. The first sum consumes all four values 0, 1, 4 and 9, totalling 14, so the second sum over the exhausted generator is 0.

More Python Programming questions

Exams that ask this topic