A nested loop is a loop inside another loop. The inner loop runs all the way through for every single pass of the outer loop. That is how you visit every square on a game board, every seat in a cinema, or every pair of players in a tournament.
THE BASIC SHAPE
Two for lines, the second one indented under the first. Watch the order the numbers come out in:
for row in range(2):
for col in range(3):
print(row, col)0 0
0 1
0 2
1 0
1 1
1 2
- The outer loop sets
rowto 0. - The inner loop then runs completely:
colis 0, 1, 2. - Only then does the outer loop move on to
row = 1, and the inner loop starts again from 0.
Think of a clock: the minute hand goes all the way around before the hour hand moves one step.
HOW MANY TIMES DOES IT RUN?
Multiply. An outer loop of 3 and an inner loop of 4 run the inner body 3 × 4 = 12 times.
squares = 0
for y in range(3):
for x in range(4):
squares = squares + 1
print(squares)12
DRAWING A GRID
This is the classic use. The outer loop picks a row, the inner loop builds that row one character at a time, then we print it.
for y in range(3):
row = ""
for x in range(5):
row = row + "."
print(row).....
.....
.....
Notice where each line sits. row = "" is in the outer loop, so every row starts empty. print(row) is also in the outer loop, so it runs once per row, after the inner loop has finished.
Now put a snake head on the board. Each square is a position (x, y), and we check if it is the head:
head = (1, 1)
for y in range(3):
row = ""
for x in range(5):
if (x, y) == head:
row = row + "@"
else:
row = row + "."
print(row).....
.@...
.....
This is exactly how a text version of Snake draws its board. Positions like (1, 1) are tuples: two values kept together.
n = 0
for a in range(3):
for b in range(4):
n = n + 1
print(n)n ends at 12. 7 would be 3 + 4: adding instead of multiplying.LOOPING OVER A LIST OF LISTS
A map or a table is often stored as a list of rows, where each row is itself a list. The outer loop takes one row, the inner loop takes each cell in it.
level = [
[0, 1, 0],
[2, 0, 1],
[0, 0, 3],
]
coins = 0
for row in level:
for cell in row:
coins = coins + cell
print("Coins on this level:", coins)Coins on this level: 7
Need the position too? Use enumerate() on both loops:
level = [
[0, 0, 0],
[0, 0, 9],
]
for y, row in enumerate(level):
for x, cell in enumerate(row):
if cell == 9:
print("Treasure at", x, y)Treasure at 2 1
EVERY PAIR: A MATCH SCHEDULE
Nested loops also give you every combination of two things. Here, every player meets every other player once:
players = ["Ada", "Bo", "Kai"]
for i in range(len(players)):
for j in range(i + 1, len(players)):
print(players[i], "vs", players[j])Ada vs Bo
Ada vs Kai
Bo vs Kai
The inner loop starts at i + 1, so nobody plays themselves and no match appears twice.
A TIMES TABLE
One more classic. end=" " keeps print on the same line, and the empty print() starts a new one.
for a in range(1, 4):
for b in range(1, 4):
print(a * b, end=" ")
print()1 2 3
2 4 6
3 6 9
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)break only leaves the inner loop. So for every i, Python prints j = 0, hits break at j = 1, and the outer loop carries on with the next i.STOPPING BOTH LOOPS
Because break only stops the loop it is in, the cleanest way to stop everything is to put the loops in a function and use return:
def find(grid, target):
for y, row in enumerate(grid):
for x, cell in enumerate(row):
if cell == target:
return (x, y)
return None
grid = [["a", "b"], ["c", "d"]]
print(find(grid, "c"))
print(find(grid, "z"))(0, 1)
None
COMMON BEGINNER MISTAKES
print(row) is probably one level too deep.for i in ...: inside another for i in ...: overwrites the outer i. Give each loop its own name, like row and col or y and x.return inside a function, or a flag variable the outer loop checks.row = "" sits before the outer loop, every row keeps growing. Reset it at the start of each outer pass.grid[y][x]: first pick the row, then the column inside it.WHAT NEXT?
New to loops? Start with for loops and lists. Ready to use the grid for real? The Snake game logic guide builds on exactly this board.
PRACTICE IT, DON'T JUST READ IT
The Grid in Snek Finale has you draw a Snake board with two loops and place the head yourself, with real Python running on your phone.
PLAY SNEK FINALE ▸FAQ
What is a nested loop in Python?
A loop written inside another loop. For every pass of the outer loop, the inner loop runs from start to finish.
How many times does a nested loop run?
Multiply the sizes. An outer loop of 3 and an inner loop of 4 run the inner body 3 × 4 = 12 times.
How do I break out of two loops in Python?
break only stops the inner loop. Put the loops in a function and use return, or set a flag variable and check it in the outer loop.
Are nested loops bad?
No. They are the normal way to work with grids and tables. They only get slow when both loops are very large, because the work multiplies.