Skip to content

Module 6 · Loops and Iteration — topic 6 of 12

Nested loops

A loop inside another loop repeats a whole inner loop for each outer iteration. Learn to build grids and tables, count total iterations, and process lists of lists.

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

Learning objectives

  • Write and trace nested loops
  • Calculate how many times the inner body runs
  • Process grids and nested lists

Definition

A loop inside another loop repeats a whole inner loop for each outer iteration. Learn to build grids and tables, count total iterations, and process lists of lists.

Introduction

A nested loop is a loop placed inside the body of another loop. For every single iteration of the outer loop, the inner loop runs completely from start to finish. Think of a clock: the minute hand goes round once for every step of the hour hand.

Why it matters

Tables, grids, seating plans, timetables and comparisons of every pair of items all have two dimensions. Nested loops are the natural way to visit every cell or every pair.

Detailed explanation

If the outer loop runs m times and the inner loop runs n times per outer iteration, the inner body runs m × n times in total.

The inner loop variable changes fastest; the outer loop variable changes only when the inner loop has finished.

Use print(..., end=" ") inside the inner loop to build a row and an empty print() after it to end the row.

Nested lists (lists of lists) represent grids: grid[row][col]. Loop over rows in the outer loop and over the items of each row in the inner loop.

break and continue affect only the innermost loop they are in.

The m × n growth means nested loops over large data can be slow; Module 18 discusses how to recognise and avoid unnecessary nesting.

Syntax

Text
for row in rows:
for item in row:
process(item)
finish_row()
  • The inner loop is indented inside the outer loop.
  • The inner loop runs fully for each outer item.
  • Code after the inner loop runs once per row.

Code examples

A small multiplication grid

Python
for a in range(1, 4):
for b in range(1, 4):
print(a * b, end="\t")
print()
Output
1	2	3	
2	4	6	
3	6	9	

Counting iterations

Python
count = 0
for i in range(4):
for j in range(5):
count += 1
print(count)
Output
20

More examples

Seat map and pair matching

Python
seats = [
["A1", "A2", "A3"],
["B1", "B2", "B3"],
]
booked = {"A2", "B1"}
for row in seats:
line = ""
for seat in row:
line += ("[X] " if seat in booked else f"{seat} ")
print(line.strip())
players = ["Ana", "Raj", "Li"]
for i in range(len(players)):
for j in range(i + 1, len(players)):
print(players[i], "vs", players[j])
Output
A1 [X] A3
[X] B2 B3
Ana vs Raj
Ana vs Li
Raj vs Li

Step-by-step explanation

  • The outer loop takes one row of the seat map; the inner loop builds a display line for it.
  • Booked seats are shown as [X]; strip() removes the trailing space.
  • In the second part, j starts at i + 1 so each pair appears once and nobody plays themselves.
  • Three players give three matches: 3 × 2 ÷ 2.

Expected output

Running “Seat map and pair matching” prints exactly:

TextOutput
A1 [X] A3
[X] B2 B3
Ana vs Raj
Ana vs Li
Raj vs Li

Practical applications

  • Spreadsheets and images are processed cell by cell or pixel by pixel with nested loops.
  • Tournament schedulers generate every pairing with nested loops.
  • Cinema booking systems display seat grids row by row.

Best practices

  • Name loop variables row/col or outer/inner, not i/j when clarity matters.
  • Keep nesting to two or three levels.
  • Estimate m × n before nesting loops over large data.

Common mistakes

Resetting at the wrong level

Avoid

line = ""
for row in grid:
for cell in row:
line += cell

Prefer

for row in grid:
line = ""
for cell in row:
line += cell

Each row needs a fresh line, so reset it inside the outer loop.

Comparing every item with itself

Avoid

for a in items:
for b in items:
pair(a, b)

Prefer

for i in range(len(items)):
for j in range(i + 1, len(items)):
pair(items[i], items[j])

Starting j at i + 1 avoids self-pairs and duplicate pairs.

Key takeaways

  • The inner loop completes fully for each outer iteration.
  • Total inner iterations = outer count × inner count.
  • Nested lists are processed row by row with nested loops.

Try it yourself

  1. 1
    Print a right-angled triangle of numbers where row n contains 1 to n.
  2. 2
    Sum all values in a 3 × 3 list of lists using nested loops.

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.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic