SyntaxStudy
Sign Up
Python Intermediate 4 min read

Nested Comprehensions

Nested Comprehensions

You can nest comprehensions to flatten matrices or generate combinations.

Example
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [x for row in matrix for x in row]
print(flat)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
Pro Tip

Read nested comprehensions left-to-right like nested for loops.