Hone

Lessons · Python · grids (a list of lists)

A grid is a list of lists

grid[row][col]. The outer list holds rows, so the first bracket picks a row and the second picks a cell inside it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Images, spreadsheets, game boards, maps, seating plans. Once the two brackets and the bounds check are automatic, every grid problem becomes the same two nested loops with different work in the middle.

How to think about it

Write the two loops first, over range(len(grid)) and range(len(grid[0])), and name them rows and cols. Then write the work for one cell. Only after that add neighbours, and only with a bounds check.

Worked example

grid = [[3, 1, 4], [1, 5, 9], [2, 6, 5]]
Three rows, three columns.
rows, cols = len(grid), len(grid[0])
Rows is the outer length; columns is one row's length.
print(rows, cols, grid[2][0])
3 3 2
total = 0
One running fact.
for r in range(rows):
Every row.
    for c in range(cols):
Every column of that row.
        total += grid[r][c]
The work, for one cell.
print(total)
36
neighbours = []
Now the cells touching the top-left one.
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
Up, down, left, right: the four-directions trick.
    r, c = 0 + dr, 0 + dc
Row 0, column 0, stepped by each direction.
    if 0 <= r < rows and 0 <= c < cols:
The bounds check, before the read, always.
        neighbours.append(grid[r][c])
Only the two that are on the grid survive it.
print(neighbours)
[1, 1]

Your turn

Guard the read so an off-grid neighbour is skipped.

if 0 <= r < len(grid) and :
    look_at(grid[r][c])

The trap

Python does not raise on a negative index; grid[-1][0] hands you the LAST row. An unguarded neighbour wraps to the far side of the grid and returns a plausible wrong answer.

Practise grids (a list of lists) on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.