Nested loops & 2-D lists
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A loop inside a loop
- You can put one loop inside another loop.
- For every pass of the outer loop, the inner loop runs fully.
- So an outer of 2 and an inner of 3 runs the body 2 × 3 = 6 times.
for row in range(2):
for col in range(3):
print(row, col)
A list of lists
- A 2-D list is a list whose items are themselves lists.
- It models a grid or table: rows of columns.
- Reach one cell with two indexes:
grid[row][col].
grid = [[1, 2], [3, 4]]
print(grid[0][1])
print(grid[1][0])
Loop over a grid
- Use a nested loop to visit every cell.
- The outer loop walks the rows; the inner loop walks the columns.
for row in grid:gives one row (a list) at a time.
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value)
In Cambridge pseudocode
- A 2-D list is the exam's 2-D array, written
ARRAY[1:rows, 1:cols].
DECLARE grid : ARRAY[1:2, 1:3] OF INTEGER
FOR r ← 1 TO 2
FOR c ← 1 TO 3
OUTPUT grid[r, c]
NEXT c
NEXT r
Now you try
- Use a nested loop in each task.
- Press Check answer to test your code.
Use a nested loop to print a 3-by-3 square of stars: three lines, each with three * characters.
Click Run to see the output here.
Add up every number in the 2-D list grid with a nested loop. Store the total in total (the answer is 21).
Click Run to see the output here.
Count how many cells in the 2-D list grid are equal to 0. Store the count in count (the answer is 3).
Click Run to see the output here.