Sub topic 4
Visiting every element with nested loops
This chapter assumes you know Python lists, for loops, range, and zero-based indexing. You should also know how a 2D array is stored as a list of row lists, and how grid[r][c] reads one cell.
The basic pattern
To visit every cell, use one loop for the rows and a second loop inside it for the columns. The outer loop picks a row. The inner loop runs across that whole row before the outer loop moves on.
grid = [[1, 2, 3], [4, 5, 6]]
rows, cols = len(grid), len(grid[0])
for r in range(rows):
for c in range(cols):
print(grid[r][c], end=" ")
print() # 1 2 3 4 5 6Read rows as the number of lists in grid, and cols as the length of one row. Here the shape is 2 by 3, so the body runs 2 × 3 = 6 times.
This order, finishing each row before starting the next, is called row-major order. A later chapter compares it with column-major order.
Choosing a loop style
You can index with range, or you can loop over the values directly. Which one you use depends on what you need.
| Goal | Loop style |
|---|---|
| Read every value | `for row in grid: for value in row:` |
| Need the position as well | `for r in range(rows): for c in range(cols):` |
| Change values in place | Index with `range` and assign to `grid[r][c]` |
grid = [[1, 2, 3], [4, 5, 6]]
# Reading: no indices needed
total = 0
for row in grid:
for value in row:
total += value
print(total) # 21
# Writing: you need indices
for r in range(len(grid)):
for c in range(len(grid[r])):
grid[r][c] *= 2
print(grid) # [[2, 4, 6], [8, 10, 12]]Using enumerate
When you want both the position and the value, enumerate is shorter than indexing with range. It also avoids repeating grid[r][c].
grid = [[1, 2, 3], [4, 5, 6]]
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value % 2 == 0:
print(f"even {value} at row {r}, column {c}")This prints the even values 2, 4, and 6 along with their positions.
Searching with early exit
A common task is finding the first cell that matches a condition. A break only leaves the inner loop, so the outer loop would keep going. A function with return stops both loops at once.
def find(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return r, c
return None
grid = [[1, 2, 3], [4, 5, 6]]
print(find(grid, 5)) # (1, 1)
print(find(grid, 9)) # NoneCommon errors
- Swapping the bounds. Using
range(cols)for the row index raisesIndexErroron any grid that is not square. Check that rows pair withlen(grid)and columns withlen(grid[0]). - Empty grids.
len(grid[0])fails whengridis[]. Guard withif not grid: returnbefore reading the column count. - Reusing the loop variable. Writing
for iin both loops hides the outer index. Userandc, oriandj, so each name has one meaning. - Relying on
len(grid[0])for uneven rows. If rows have different lengths, uselen(grid[r])in the inner loop.
Exercise
Write a function count_value(grid, target) that returns how many cells equal target. For [[1, 2, 2], [2, 5, 6]] and target 2, what should it return, and how many times does the inner loop body run?
Show answer
It returns 3. The inner body runs 6 times, once per cell (2 rows × 3 columns). def count_value(grid, target): count = 0 for row in grid: for value in row: if value == target: count += 1 return count
Exercise
A learner writes for r in range(len(grid)): for c in range(len(grid)): print(grid[r][c]) on a 2 by 3 grid. What happens, and how do you fix it?
Show answer
The inner loop uses len(grid), which is 2 (the row count), so it reads only columns 0 and 1 and silently skips column 2. On a 3 by 2 grid it would raise IndexError instead. Fix it with range(len(grid[r])) for the inner loop.