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])?

  1. The generator stores its values in a compressed list
  2. The generator computes all values first and then deletes them
  3. The generator hands values to sum one at a time and never builds a full list
  4. 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

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