Nested Loops and Grid Traversal
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)When dealing with two-dimensional data such as tables, matrices, or screen coordinates, we nest one loop inside another.
Inner and outer loops
Nested loop is a loop placed inside the body of another loop. For every round of the outer loop, the inner loop runs all of its rounds from the start.
For every single cycle of the outer loop, the inner loop completes all of its iterations.
for i in range(1, 3): for j in range(1, 4): print(f"({i}, {j})", end=" ") print()Example 1 · Counting shifts in a roster
rounds = 0for day in range(1, 4): for shift in range(1, 3): rounds += 1print(f"Total shifts: {rounds}")Total shifts: 6
What this code does
- There are 3 days, and each day has 2 shifts.
- The inner body runs 3 * 2 = 6 times, so
roundsends at 6.
The inner loop runs 3 times for i=1 and 3 times for i=2, producing a 2 * 3 coordinate grid.
Generating multiplication tables
Nested loops calculate tabular products by multiplying row and column indices.
for row in range(1, 4): for col in range(1, 4): print(f"{row * col:2}", end=" ") print()Example 2 · Times table grid
for row in range(1, 4): for col in range(1, 6): print(f"{row * col:3}", end="") print()1 2 3 4 5 2 4 6 8 10 3 6 9 12 15
What this code does
{row * col:3}pads each number to a width of 3, so the columns line up.end=""keeps the numbers of one row on the same line.- The empty
print()after the inner loop starts a new line for the next row.
The :2 format specifier aligns numbers in neat columns.
Pattern printing
Pattern is a shape drawn with characters. The outer loop picks the row, and the inner loop or a string repeat decides what that row contains.
Generate triangles and pyramids by making the inner loop range depend on the outer loop index.
for r in range(1, 4): print("*" * r)Example 3 · Centred pyramid
rows = 4for r in range(1, rows + 1): print(" " * (rows - r) + "*" * (2 * r - 1))* *** ***** *******
What this code does
- Row
rhasrows - rspaces and then2 * r - 1stars. - The star count grows by 2 each row, which gives the pyramid its shape.
" " * nrepeats a space n times, so no inner loop is needed.
Example 4 · Number triangle
size = 3for r in range(1, size + 1): for c in range(1, r + 1): print(c, end=" ") print()1 1 2 1 2 3
What this code does
- Prints a number triangle where row
rprints numbers from 1 tor. - Row 1 prints 1; row 2 prints 1 2; row 3 prints 1 2 3.
In Python, string multiplication "*" * r often elegantly replaces manual inner loops for simple character patterns.
Next step
Check your understanding
10 quick questions