What is the output of the following Python code? g = (x * 2 for x in range(3)); print(sum(g), sum(g))
Correct answer D. 6 0
Explanation
A generator expression produces its values only once. The first sum() consumes 0, 2 and 4 to give 6, leaving the generator exhausted, so the second sum() sees no items and returns 0. If you need to iterate repeatedly, store the values in a list or create a fresh generator.
Answer checked How we write and check questions
Discussion