0
0
PythonHow-ToBeginner · 3 min read

How to Use Nested List Comprehension in Python

Use nested list comprehension by placing one list comprehension inside another. The outer comprehension loops over the main sequence, while the inner one loops over a sub-sequence, creating a nested list in a single, readable line.
📐

Syntax

A nested list comprehension has an outer for loop and one or more inner for loops inside it. The general form is:

[expression for outer_item in outer_iterable for inner_item in inner_iterable]

Here, expression can use both outer_item and inner_item. The inner loop runs fully for each outer loop iteration.

python
[expression for outer_item in outer_iterable for inner_item in inner_iterable]
💻

Example

This example creates a multiplication table from 1 to 3 using nested list comprehension. It shows how the inner loop runs for each outer loop value.

python
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]]
⚠️

Common Pitfalls

One common mistake is reversing the order of loops, which changes the output structure. Another is forgetting that the inner loop runs completely for each outer loop iteration, which can cause unexpected results or performance issues.

Also, avoid using complex expressions inside nested comprehensions that reduce readability.

python
wrong = [[j * i for i in range(1, 4)] for j in range(1, 4)]  # loops reversed
right = [[i * j for j in range(1, 4)] for i in range(1, 4)]  # correct order
print('Wrong:', wrong)
print('Right:', right)
Output
Wrong: [[1, 2, 3], [1, 2, 3], [1, 2, 3]] Right: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
📊

Quick Reference

  • Outer loop runs first, inner loop runs fully each time.
  • Use nested list comprehension for creating 2D lists or flattening lists.
  • Keep expressions simple for readability.

Key Takeaways

Nested list comprehensions combine multiple loops in one concise line.
The inner loop completes fully for each iteration of the outer loop.
Order of loops matters and affects the output structure.
Use nested comprehensions for creating or transforming nested lists efficiently.
Keep expressions simple to maintain code readability.