Comprehensions & Generators · Question 10 · Medium
The same generator expression is passed to sum twice. What do the two calls return?
g = (n * n for n in range(4))
print(sum(g), sum(g))
- 14 14
- 14 0
- 14 None
- 6 6
Answer and explanation
Answer: B. 14 0
Explanation: The first sum consumes the generator: 0 + 1 + 4 + 9 = 14. A generator cannot be rewound, so the second sum sees no values and returns 0.
Previous: A comprehension has two for clauses, one over range(2) and one over a string… · Next: One value is taken from a generator function with next before the rest is…
Practise comprehensions & generators
Try a fresh set of comprehensions & generators questions with an explanation after every answer, free and without signing up: Comprehensions & Generators practice. Or sit a full placement mock test.
More comprehensions & generators questions
- What does calling next(g) do when g is a generator that still has values left?
- A conditional expression is used in the output part of a comprehension to mark…
- A comprehension has two for clauses, one over range(2) and one over a string…
- One value is taken from a generator function with next before the rest is…
- filter is called with None as its function on a list of mixed values. Which…
- A comprehension walks through a list of rows and keeps only the odd values…
- Kavya has to add up one crore numbers read from a sensor. Why is sum(x for x…
- A dictionary comprehension swaps keys and values of a price list in which two…
- The generator function below contains print calls around its yield. In what…
- A list comprehension uses a loop variable with the same name as a module-level…
More python practice
Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge