Comprehensions & Generators · Question 13 · Medium
A comprehension walks through a list of rows and keeps only the odd values. What is the flattened result?
grid = [[1, 2], [3, 4], [5, 6]]
print([v for row in grid for v in row if v % 2])
- [2, 4, 6]
- [1, 3, 5]
- [[1], [3], [5]]
- [1, 2, 3, 4, 5, 6]
Answer and explanation
Answer: B. [1, 3, 5]
Explanation: The outer loop takes each row and the inner loop takes each value, giving one flat list. v % 2 is 1 (truthy) only for odd numbers, so 1, 3 and 5 are kept.
Previous: filter is called with None as its function on a list of mixed values. Which… · Next: Kavya has to add up one crore numbers read from a sensor. Why is sum(x for x…
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
- 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…
- 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…
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