Introduction
A loop's body can contain another loop. For every single round of the outer loop, the inner loop runs all of its rounds.
Many things in the world are two-dimensional: seats in a cinema, days in a calendar, pixels on a screen. A loop inside a loop is the natural way to visit every combination of row and column.
How it works
Every combination
colors = ["red", "blue"]
sizes = ["S", "M"]
for c in colors:
for s in sizes:
print(c, s)Two choices for colour times two for size gives four combinations. In general, an outer loop of n rounds around an inner loop of m rounds runs the inner body n × m times.
break in a nested loop
for i in range(1, 4):
for j in range(1, 4):
if j > i:
break
print(i, j)break leaves only the loop it is in. When j > i, the inner loop stops, but the outer loop carries on with the next i. That is why each row prints one more pair than the last.
Syntax
for row in range(3):
for col in range(4):
print(row, col)
Example
for row in range(1, 4):
for col in range(1, 4):
print(row * col, end=" ")
print()Watch row and col in the variables panel. row stays at 1 while col goes 1, 2, 3; then row becomes 2 and col starts again from 1. end=" " keeps the numbers on one line, and the empty print() ends each row.
Line by line
- The outer
forsetsrowto 1. - The inner
forsetscolto 1, 2 and 3 in turn. print(row * col, end=" ")prints one value and stays on the same line.- After the inner loop ends,
print()finishes the row. - The outer loop moves to the next
row, and the inner loop starts again from 1.
Expected result
1 2 3
2 4 6
3 6 9
In the real world
Spreadsheets, timetables and image filters all work row by row and column by column. Nested loops are also where programs often become slow, because the work is multiplied.
Common mistakes
- Reusing the same variable name for both loops: the inner loop overwrites the outer one's value.
- Putting the row-ending
print()inside the inner loop, which prints a new line after every value. - Expecting
breakto stop both loops. Use a flag variable, or put the loops in a function andreturn.
Best practices
- Name the variables after what they mean, such as
rowandcol. - Check where the row-ending
print()sits. - Move an inner loop into a function if the code gets hard to follow.
Summary
A nested loop runs the inner loop completely for each round of the outer loop, so the work multiplies. end keeps output on one line, and break leaves only the loop it is in.
Practice
Print a right triangle of numbers for n = 4: line i shows the numbers 1 to i, separated by spaces.
Quick check
Key takeaways
- The inner loop runs all its rounds for every round of the outer loop.
- n outer rounds around m inner rounds run the body n times m times.
- break leaves only the innermost loop.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.