Nested List Comprehension is a list comprehension inside another list comprehension — usually used to create multi-dimensional lists or flatten nested data structures.
[expression for outer in outer_iterable
for inner in inner_iterable]
You can also use conditions and multiple loops inside it.
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)
[[0, 1, 2],
[0, 1, 2],
[0, 1, 2]]
Outer loop: Rows (i in range(3)
)
Inner loop: Columns (j in range(3)
)
nested = [[1, 2, 3], [4, 5, 6], [7, 8]]
flat = [num for sublist in nested for num in sublist]
print(flat)
[1, 2, 3, 4, 5, 6, 7, 8]
table = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(table)
[[1, 2, 3],
[2, 4, 6],
[3, 6, 9]]
result = [[i*j for j in range(1, 4) if j != 2] for i in range(1, 4)]
print(result)
[[1, 3], [2, 6], [3, 9]]
✅ When you want compact, readable code for:
2D arrays or matrices
Flattening nested structures
Applying multiple filters/loops in one line
Avoid over-nesting — it can reduce readability
Break into normal loops if logic is too complex