Comprehensions & Generators · Question 5 · Easy

Which of these expressions creates a generator object rather than a fully built collection?

  1. [n * 2 for n in data]
  2. {n * 2 for n in data}
  3. (n * 2 for n in data)
  4. {n: n * 2 for n in data}
Answer and explanation

Answer: C. (n * 2 for n in data)

Explanation: Round brackets around a comprehension give a generator expression, which produces values lazily. Square brackets build a list, and braces build a set or a dict.

Previous: A set comprehension collects the first letter of each word. What does len… · Next: The built-in len is passed to map for a list of city names. What does this…

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