Comprehensions & Generators questions and answers
List, dict and set comprehensions, yield and lazy evaluation. Practise comprehensions & generators questions from the python section of placement tests, with a worked explanation after every answer. Practice is free and needs no sign-up.
Sample comprehensions & generators questions with worked answers
Question 1
Which of these expressions creates a generator object rather than a fully built collection?
- [n * 2 for n in data]
- {n * 2 for n in data}
- (n * 2 for n in data)
- {n: n * 2 for n in data}
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.
Question 2
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: 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.
Question 3
The generator function below contains print calls around its yield. In what order do the letters appear?
def numbers():
print("A")
yield 1
print("B")
g = numbers()
print("C")
next(g)
print("D")
- A C D
- A C B D
- C A B D
- C A D
Answer: D. C A D
Explanation: Calling numbers() only creates the generator; none of its body runs yet, so C is printed first. next(g) runs the body up to the yield, printing A, and B is never reached because the generator is not resumed again.
All 20 comprehensions & generators questions with answers
- A list comprehension applies a string method to every company name. What does…
- A comprehension with an if clause keeps only the passing marks (60 or more)…
- A dictionary comprehension maps each number to its square. What is printed?
- A set comprehension collects the first letter of each word. What does len…
- Which of these expressions creates a generator object rather than a fully…
- The built-in len is passed to map for a list of city names. What does this…
- 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…
- The same generator expression is passed to sum twice. What do the two calls…
- 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…
- 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…
Comprehensions & Generators: common questions
What are comprehensions & generators questions?
List, dict and set comprehensions, yield and lazy evaluation. They appear in the python section of many placement tests.
Where can I practise comprehensions & generators questions with answers for free?
Right here on LogicWiz Exams. Every comprehensions & generators question has a worked explanation after you answer. Practice is free and needs no sign-up.
How should I practise comprehensions & generators?
Start with easy questions, then move to medium and hard. Read the explanation after each answer, and come back to the ones you missed.
Start practising
On this page you can start a fresh set of comprehensions & generators questions, choose easy, medium or hard, and time yourself if you want to. Or practise the whole subject: Python practice.
More python topics
- Variables, Types & Operators: Dynamic typing, numbers, operators, precedence and truthiness.
- Python Strings: Indexing, slicing, methods, formatting and immutability.
- Lists & Tuples: Slicing, methods, copies, sorting and unpacking.
- Dictionaries & Sets: Lookups, iteration, hashable keys and set operations.
- Conditions & Loops: if/elif, for, while, range, break, continue and loop else.
- Functions & Scope: Arguments, defaults, *args, closures, lambda and recursion.
- Classes & Objects: Attributes, inheritance, super(), dunder methods and properties.
- Exceptions & Files: try/except/else/finally, raising errors and the with statement.
- Built-ins & Standard Library: sorted, zip, any/all, collections, itertools and imports.
Other subjects
- Quantitative Aptitude: Arithmetic, percentages, time and work, speed, probability and data interpretation: the numerical section of every fresher test.
- Logical Reasoning: Series, coding-decoding, arrangements, syllogisms and puzzles: the section that separates prepared candidates from the rest.
- Verbal Ability: Vocabulary, grammar, reading comprehension and sentence order: tested in nearly every IT services hiring exam.
- Technical & Programming: CS fundamentals, output prediction and pseudo-code: the technical MCQ round for IT roles.
- SQL: SQL quizzes by topic, from SELECT and joins to window functions: query output and concepts for analyst and developer roles.
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge · Test from a job description · LogicWiz Open: free team quiz · Free interview prep