Comprehensions & Generators · Question 14 · Medium
Kavya has to add up one crore numbers read from a sensor. Why is sum(x for x in readings) lighter on memory than sum([x for x in readings])?
- The generator stores its values in a compressed list
- The generator computes all values first and then deletes them
- The generator hands values to sum one at a time and never builds a full list
- sum skips duplicate values when it is given a generator
Answer and explanation
Answer: C. The generator hands values to sum one at a time and never builds a full list
Explanation: A generator expression is lazy: each value is produced only when sum asks for it and is then discarded. The list comprehension first builds a complete list of one crore items in memory.
Previous: A comprehension walks through a list of rows and keeps only the odd values… · Next: A dictionary comprehension swaps keys and values of a price list in which two…
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
- 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…
- 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…
- The in operator is used twice on the same generator before it is turned into a…
- A nested list comprehension is applied to a 2 × 3 matrix. What does it produce?
- The name arr is rebound to a new list after a generator expression is created…
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