Python › Comprehensions & Generators
How do you write a nested comprehension, like flattening a list of lists into a single flat list?
IntermediateAnswer
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.