Why Nest Loops?

Nested loops let you combine two dimensions of iteration — for example, rows × columns, or every pair of items.

Times Table

for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i*j:3}", end=" ")
    print()

Walking a 2D List

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
for row in grid:
    for value in row:
        print(value, end=" ")
    print()

Using Indices

for r in range(len(grid)):
    for c in range(len(grid[r])):
        print(f"grid[{r}][{c}] = {grid[r][c]}")

Breaking Out of Both Loops

found = False
for r in range(len(grid)):
    for c in range(len(grid[r])):
        if grid[r][c] == 5:
            found = True
            break
    if found:
        break
🎯 HKDSE 2D-list questions almost always appear in Paper 1B. Practice row-major vs column-major traversal until it is automatic.

Practise this on PyForm — free

PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.

Open PyForm →