Comprehensions & Generators · Question 19 · Hard
A nested list comprehension is applied to a 2 × 3 matrix. What does it produce?
m = [[1, 2, 3], [4, 5, 6]]
print([[row[i] for row in m] for i in range(3)])
- [[1, 2, 3], [4, 5, 6]]
- [1, 4, 2, 5, 3, 6]
- [[1, 2], [3, 4], [5, 6]]
- [[1, 4], [2, 5], [3, 6]]
Answer and explanation
Answer: D. [[1, 4], [2, 5], [3, 6]]
Explanation: For each column index i the inner comprehension picks row[i] from every row, so each inner list is one column. This turns rows into columns, which is the transpose.
Previous: The in operator is used twice on the same generator before it is turned into a… · Next: The name arr is rebound to a new list after a generator expression is created…
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 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…
- 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