Nested Loops
A nested loop is a loop inside another loop. The inner loop runs completely for every single pass of the outer loop. Nested loops are the natural tool for anything shaped like a grid: tables, seating plans, game boards and pairs of items.
How nested loops run
Read the code below slowly. The outer loop picks a value for row; then the inner loop runs all the way through for that row before the outer loop moves on.
for row in range(1, 3):
for col in range(1, 4):
print("row", row, "col", col)
print("-- end of row", row)
The outer loop runs 2 times and the inner loop runs 3 times per outer pass, so the innermost print() runs 2 × 3 = 6 times. The print("-- end of row", row) line is indented only once, so it belongs to the outer loop and runs after each inner loop finishes.
print() runs. The inner loop finishes a whole row before the outer loop moves to the next row.Printing a multiplication table
Using end="" keeps the inner loop's output on one line, and an empty print() after the inner loop starts the next row. The format specifier :4 in the f-string pads each number to 4 characters wide so the columns line up.
for i in range(1, 5):
for j in range(1, 5):
print(f"{i * j:4}", end="")
print() # move to the next line
Drawing patterns
Patterns are a classic way to practise nested loops. Here the inner loop's range depends on the outer loop's variable, so each row is longer than the last.
for row in range(1, 5):
for star in range(row):
print("*", end="")
print()
(In real code, print("*" * row) does the same job in one loop, but the nested version shows how the inner range can change on every outer pass.)
Working with pairs
Nested loops can combine every item of one collection with every item of another. This prints every home-and-away fixture for three football teams, skipping a team playing itself:
teams = ["Gor Mahia", "AFC Leopards", "Tusker"]
for home in teams:
for away in teams:
if home != away:
print(home, "vs", away)
Looping through a grid (a list of lists)
A list can contain other lists. Each inner list can represent a row, which makes a grid. The outer loop takes one row at a time, and the inner loop takes each item in that row.
seats = [
["A1", "A2", "A3"],
["B1", "B2", "B3"],
["C1", "C2", "C3"],
]
for row in seats:
for seat in row:
print(seat, end=" ")
print()
This pattern also works for adding up a table of numbers, such as a week of sales for each mama mboga stall in a market.
sales = [
[1200, 900, 1500], # stall 1, three days
[800, 1100, 950], # stall 2
]
grand_total = 0
for stall in sales:
for amount in stall:
grand_total += amount
print("Grand total: KES", grand_total)
Breaking out of nested loops
break only leaves the loop it's directly inside (see Break, Continue & Pass). To stop both loops, a common approach is a flag variable that the outer loop checks.
grid = [
[3, 8, 1],
[6, 0, 4],
[7, 2, 0],
]
found = False
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == 0:
print("First zero at row", r, "column", c)
found = True
break # leaves the inner loop
if found:
break # leaves the outer loop
A cleaner alternative is to put the loops inside a function and use return, which exits everything at once. You'll learn that on Return Values.
Nested loops multiply the work. Two loops over 1,000 items each run the inner block 1,000,000 times, which can make a program noticeably slow. Before nesting loops over large data, ask whether a set or dictionary lookup could avoid the inner loop.
Getting the indentation of the "end of row" print() wrong. Indent it once and it runs after each row; indent it twice and it runs after every single item; don't indent it and it runs only once, after both loops have finished. Also, use different variable names for the inner and outer loops, such as i and j, never the same name twice.
Key points
- The inner loop runs completely for every pass of the outer loop, so total runs = outer × inner.
- Nested loops suit grids, tables, patterns and pairs of items.
- Use
end=""and an emptyprint()to build rows of output. breakexits only the inner loop; use a flag or a function'sreturnto exit both.- Watch performance: nested loops over big collections get slow quickly.
Tip: use the ← and → keys to move between pages.
