Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Edge case: A generator expression is consumed twice.

Edge case: A generator expression is consumed twice.
g = (x * x for x in range(4))
print(sum(g), sum(g))
What is printed?
  1. A. 14 14
  2. B. 0 14
  3. C. It raises StopIteration
  4. D. 14 0

Correct answer: D. 14 0

A generator can be iterated only once. The first sum consumes 0 + 1 + 4 + 9 = 14; the second finds it exhausted and returns 0 (sum of nothing) without raising. Use a list if the values are needed twice.

More Coding Interview Problems questions

Exams that ask this topic