Advertisement
Intermediate Python, Comprehensions & Generators

How do you write a nested comprehension, like flattening a list of lists into a single flat list?

Short answer

Chain multiple 'for' clauses in the SAME order you'd nest equivalent for loops — the outer loop comes first, inner loops follow, letting you flatten nested structures or produce combinations in a single comprehension expression.

Save Python mock interview
Advertisement
AModel answer
Chain multiple 'for' clauses in the SAME order you'd nest equivalent for loops — the outer loop comes first, inner loops follow, letting you flatten nested structures or produce combinations in a single comprehension expression.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Real-world example
Flattening a 2D grid or matrix of values into a single flat list for further processing.
Likely follow-ups
  • At what point does a nested comprehension become hard enough to read that a regular for loop is clearer?
Related topics