Nested Loops, break and continue in Python
Nested Loops: A Loop Inside a Loop
A loop's block can contain another loop. This is called a nested loop. For every single iteration of the outer loop, the inner loop runs all the way through.
for shirt in ["red", "blue"]:
for size in ["S", "M", "L"]:
print(shirt, size)red S red M red L blue S blue M blue L
Think of it like a clock: for every one step of the hour hand, the minute hand goes all the way round.
How it runs
- The outer loop takes
"red". - The inner loop runs completely:
S,M,L. - The outer loop takes
"blue", and the inner loop starts again fromS.
So the inner block runs 2 x 3 = 6 times: outer count times inner count.
Read the indentation
- The outer
forsits at the left edge. - The inner
foris indented 4 spaces: it's inside the outer loop. - The inner block is indented 8 spaces: it's inside both loops.
It's the same idea as the nested if from chapter 8: each level adds 4 spaces.
With range()
Nested range() loops make every pair of numbers. Here is a small times table:
for a in range(1, 3):
for b in range(1, 4):
print(a, "x", b, "=", a * b)
print("---")1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 --- 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 ---
The print("---") is indented 4 spaces, so it's inside the outer loop but after the inner one. It runs once per row, when the inner loop has finished.
Common beginner doubt: "Can I use the same variable name for both loops?" Don't. The inner loop would overwrite the outer one's value. Give each loop its own name, like a and b, or row and col.
For each outer item, the inner loop runs all the way through.