Loops · Lesson 13 of 39
Nested Loops and Loop Patterns
A loop inside another loop is called a nested loop. It is how you work with anything two-dimensional – rows and columns, seats in a cinema, pixels in an image – and it is behind the famous "print this pattern" questions in coding tests.
In this lesson
- How the inner loop runs completely for every outer pass
- Tables and grids
- Star and number patterns, step by step
- Breaking out of nested loops cleanly
How nested loops run
for row in range(1, 4):
for col in range(1, 3):
print(f"(row {row}, col {col})")
(row 1, col 1) (row 1, col 2) (row 2, col 1) (row 2, col 2) (row 3, col 1) (row 3, col 2)
The inner loop finishes all its passes before the outer loop moves on – exactly like the hands of a clock: the minute hand goes all the way round for every step of the hour hand. 3 outer passes × 2 inner passes = 6 lines.
Outer and inner
- Outer loop: row = 1, 2, 3moves one step…
- Inner loop: col = 1, 2…only after the inner loop has completed all its steps
- Total work = outer × inner3 × 2 = 6 runs of the inner block
A multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i * j:4}", end="")
print() # new line after each row
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Two tricks make grids work: end="" keeps the inner prints on one line, and the empty print() after the inner loop moves to the next row.
Pattern programs
Pattern questions test whether you can turn a picture into loop rules. The method is always the same: write down what each row contains as a function of the row number.
Right triangle
n = 5
for row in range(1, n + 1):
print("* " * row)
* * * * * * * * * * * * * * *
Row r has r stars. Python's string repetition ("* " * row) replaces the inner loop.
Pyramid
| Row | Spaces | Stars |
|---|---|---|
| 1 | 4 | 1 |
| 2 | 3 | 3 |
| 3 | 2 | 5 |
| r | n − r | 2r − 1 |
n = 5
for r in range(1, n + 1):
print(" " * (n - r) + "*" * (2 * r - 1))
* *** ***** ******* *********
Number triangle (with a real inner loop)
for r in range(1, 5):
for c in range(1, r + 1):
print(c, end=" ")
print()
1 1 2 1 2 3 1 2 3 4
Floyd's triangle
number = 1
for r in range(1, 5):
for _ in range(r):
print(f"{number:3}", end="")
number += 1
print()
1 2 3 4 5 6 7 8 9 10
The name _ is a convention for "I need a loop variable but I won't use it".
Searching a grid
A cinema hall as a list of rows; find the first free seat (0 = free, 1 = booked):
hall = [
[1, 1, 1, 1],
[1, 1, 0, 1],
[0, 0, 0, 0],
]
found = None
for r, row in enumerate(hall):
for c, seat in enumerate(row):
if seat == 0:
found = (r + 1, c + 1)
break # leaves the inner loop only
if found:
break # leaves the outer loop too
print("First free seat (row, seat):", found)
First free seat (row, seat): (2, 3)
Common mistake: expecting break to exit every loop
break leaves only the innermost loop. To stop both, check a flag in the outer loop (as above) or, cleaner, put the search in a function and return as soon as you find the answer.
A word on speed
Nested loops multiply work: two loops over 1,000 items each mean a million passes. That is fine for small data, but in interviews you will be asked to replace nested loops with a set or dict lookup where possible. Chapter 8 shows how.
Practice
Try it yourself
Print an inverted right triangle of stars with 4 rows.
Show solution
for r in range(4, 0, -1): print("*" * r)**** *** ** *
Print all pairs (a, b) with 1 ≤ a < b ≤ 4.
Show solution
for a in range(1, 5): for b in range(a + 1, 5): print((a, b), end=" ")(1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4)
Print this hollow square of size 4:
**** * * * * ****Show solution
n = 4 for r in range(n): if r == 0 or r == n - 1: print("*" * n) else: print("*" + " " * (n - 2) + "*")**** * * * * ****
Quick check
How many times does the inner print run in for i in range(4): for j in range(3): print()?
12 (4 × 3).
Which loop does break exit in nested loops?
Only the innermost loop that contains it.
In a pyramid of height n, how many stars are in row r?
2r − 1, preceded by n − r spaces.
Summary
- The inner loop completes fully for every pass of the outer loop.
- Use
end=""and an emptyprint()to build rows. - Solve patterns by writing each row's content as a formula of the row number.
breakexits one loop; use a flag orreturnto exit several.
Test yourself with real interview problems: Python coding interview questions (part 1).
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.