Practice mode Python

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.