Some text some message..
Back 🧠 What is Nested List Comprehension? 25 Jun, 2025

Nested List Comprehension is a list comprehension inside another list comprehension — usually used to create multi-dimensional lists or flatten nested data structures.


✅ Syntax

[expression for outer in outer_iterable
            for inner in inner_iterable]

You can also use conditions and multiple loops inside it.


🔸 Example 1: Create a 3x3 Matrix

matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)

🔹 Output:

[[0, 1, 2],
 [0, 1, 2],
 [0, 1, 2]]
  • Outer loop: Rows (i in range(3))

  • Inner loop: Columns (j in range(3))


🔸 Example 2: Flatten a 2D List

nested = [[1, 2, 3], [4, 5, 6], [7, 8]]
flat = [num for sublist in nested for num in sublist]
print(flat)

🔹 Output:

[1, 2, 3, 4, 5, 6, 7, 8]

🔸 Example 3: Multiplication Table (1–3)

table = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(table)

🔹 Output:

[[1, 2, 3],
 [2, 4, 6],
 [3, 6, 9]]

🔸 Example 4: Conditional Nested Comprehension

result = [[i*j for j in range(1, 4) if j != 2] for i in range(1, 4)]
print(result)

🔹 Output:

[[1, 3], [2, 6], [3, 9]]

🧠 When to Use Nested List Comprehension?

✅ When you want compact, readable code for:

  • 2D arrays or matrices

  • Flattening nested structures

  • Applying multiple filters/loops in one line


⚠️ Caution

  • Avoid over-nesting — it can reduce readability

  • Break into normal loops if logic is too complex