Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 3 of 13

Nested comprehensions

Comprehensions with several for clauses (flattening and combining) and comprehensions inside comprehensions (building 2-D structures), and how to read their order.

Beginner 12 min read·Lesson 147 of 306 in Python Programming

Learning objectives

  • Read multi-for comprehensions in the correct order
  • Flatten a list of lists
  • Build a 2-D grid with a comprehension inside a comprehension

Definition

A nested comprehension either has multiple for clauses in one comprehension, which run like nested loops from left to right, or contains another comprehension as its output expression, which builds nested structures such as lists of lists.

Introduction

[(r, c) for r in range(2) for c in range(3)] produces every combination of r and c. [[0] * 3 for _ in range(2)] builds a 2 × 3 grid. Both are nested comprehensions, but they work differently.

Why it matters

Flattening lists, generating combinations and building grids are everyday tasks; nested comprehensions do them concisely — and also avoid the famous [[0] * 3] * 2 aliasing bug.

Detailed explanation

Multiple for clauses run left to right like nested loops written top to bottom: [x for row in grid for x in row] means for row in grid: for x in row: collect x. The result is flat.

A comprehension as the output expression creates one inner list per outer item: [[r * c for c in range(3)] for r in range(3)] builds rows.

Reading tip: in a multi-for comprehension, the for clauses appear in the same order as in the equivalent nested loop; only the expression moves to the front.

[[0] * 3] * 2 creates two references to the same inner list, so changing one row changes both. [[0] * 3 for _ in range(2)] creates independent rows.

Beyond two levels, nested comprehensions become hard to read; use loops or helper functions.

Syntax

Python
flat = [x for row in matrix for x in row] # flatten
pairs = [(a, b) for a in A for b in B] # combinations
grid = [[0 for c in range(cols)] for r in range(rows)] # 2-D
  • Multiple for clauses: left to right, flat result.
  • Inner comprehension: nested result.

Code examples

Flattening and combining

Python
matrix = [[1, 2, 3], [4, 5], [6]]
print([x for row in matrix for x in row])
sizes = ["S", "M"]
colours = ["red", "blue"]
print([f"{s}-{c}" for s in sizes for c in colours])
Output
[1, 2, 3, 4, 5, 6]
['S-red', 'S-blue', 'M-red', 'M-blue']

Building a grid safely

Python
wrong = [[0] * 3] * 2
wrong[0][0] = 9
print(wrong)
right = [[0] * 3 for _ in range(2)]
right[0][0] = 9
print(right)
Output
[[9, 0, 0], [9, 0, 0]]
[[9, 0, 0], [0, 0, 0]]

More examples

Tables and transposition

Python
table = [[r * c for c in range(1, 5)] for r in range(1, 4)]
for row in table:
print(row)
transposed = [[row[i] for row in table] for i in range(len(table[0]))]
print(transposed)
pairs = [(a, b) for a in range(1, 5) for b in range(a, 5) if a + b == 5]
print(pairs)
Output
[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
[[1, 2, 3], [2, 4, 6], [3, 6, 9], [4, 8, 12]]
[(1, 4), (2, 3)]

Step-by-step explanation

  • The outer comprehension makes one row per r; the inner one fills the row with r × c.
  • Transposing builds one new row per column index i, collecting row[i] from every row.
  • The last comprehension has two for clauses (b starts at a, so each pair appears once) and a filter.

Expected output

Running “Tables and transposition” prints exactly:

TextOutput
[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
[[1, 2, 3], [2, 4, 6], [3, 6, 9], [4, 8, 12]]
[(1, 4), (2, 3)]

Practical applications

  • Flattening nested API results.
  • Generating all combinations of product options.
  • Initialising game boards and matrices.

Best practices

  • Limit comprehensions to two for clauses.
  • Use itertools.product for combinations of many iterables.
  • Always build grids with an inner comprehension or loop.

Common mistakes

Shared inner lists

Avoid

board = [["."] * 3] * 3

Prefer

board = [["."] * 3 for _ in range(3)]

List multiplication repeats the same inner list object.

Reversed for clauses

Avoid

[x for x in row for row in matrix]

Prefer

[x for row in matrix for x in row]

Clauses run left to right; row must be defined before it is used.

Important notes

  • zip(*table) is a shorter way to transpose: list(map(list, zip(*table))).

Key takeaways

  • Several for clauses act like nested loops, left to right.
  • An inner comprehension builds nested lists.
  • [[0]*n]*m shares rows — avoid it.

Try it yourself

  1. 1
    Flatten a list of sentences into a list of words.
  2. 2
    Build a 5×5 identity matrix with a nested comprehension.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this topic