Sub topic 2
Reading and writing elements with two indices
This chapter assumes you know Python lists, zero-based indexing, and basic for loops. It also assumes you have seen a 2D array as a list of rows. Here you will learn how a pair of indices selects one cell, how to update cells, and which errors to expect.
The two-index model
A 2D array in Python is usually a list of lists. The outer list holds the rows. Each inner list holds the values in one row. To reach a single cell, you give two indices:
- The first index selects the row.
- The second index selects the column.
Both start at 0. In grid[r][c], Python first evaluates grid[r], which returns the row list. It then evaluates [c] on that row.
grid = [
[1, 2, 3],
[4, 5, 6],
]
rows = len(grid) # 2
cols = len(grid[0]) # 3
print(grid[1][2]) # 6 (row 1, column 2)
grid[0][1] = 20
print(grid) # [[1, 20, 3], [4, 5, 6]]len(grid) gives the number of rows. len(grid[0]) gives the number of columns, because it measures the first row. The shape of this grid is 2 by 3, written m by n with m rows and n columns.
Writing a value
Assignment uses the same two indices. The expression grid[0][1] = 20 fetches row 0, then replaces the item at position 1 in that row. Only that one cell changes.
grid = [[1, 2, 3], [4, 5, 6]]
grid[1][0] = 40
grid[0][2] += 10 # read, add, write back
print(grid) # [[1, 2, 13], [40, 5, 6]]You can also replace a whole row with grid[0] = [7, 8, 9]. The new row should have the same length as the others, or the array stops being rectangular.
Negative indices
Negative indices count from the end. grid[-1] is the last row and grid[0][-1] is the last element of the first row.
grid = [[1, 2, 3], [4, 5, 6]]
print(grid[-1][-1]) # 6, the bottom-right cell
print(grid[-1][0]) # 4, first cell of the last rowThis is convenient for corners. It is also a source of silent bugs. If a calculation produces -1 by mistake, Python does not complain. It reads from the far edge.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Row index too large, such as `grid[2][0]` on a 2-row grid | `IndexError` from the outer list | Check `0 <= r < len(grid)` |
| Column index too large, such as `grid[0][3]` on a 3-column grid | `IndexError` from the inner list | Check `0 <= c < len(grid[r])` |
| Swapping the indices, such as `grid[c][r]` | Wrong cell, or an `IndexError` on non-square grids | Always write row first, then column |
| Computed index of `-1` | Wraps to the last row or column with no error | Test bounds explicitly |
The swapped-index mistake is the most common. On a square grid it returns a valid but wrong value, so tests can pass while the program is incorrect. Name your variables r and c (or row and col) rather than i and j to keep the order clear.
Safe access with a helper
A small function keeps bounds checks in one place:
def get(grid, r, c, default=None):
if 0 <= r < len(grid) and 0 <= c < len(grid[r]):
return grid[r][c]
return default
grid = [[1, 2, 3], [4, 5, 6]]
print(get(grid, 1, 2)) # 6
print(get(grid, 2, 0)) # None
print(get(grid, 0, -1)) # None (the check rejects negatives)The check tests the row first, so grid[r] is only evaluated when r is valid. Using len(grid[r]) instead of len(grid[0]) also works for rows of different lengths.
Exercise
Given grid = [[1, 2, 3], [4, 5, 6]], what does grid[0][-1] + grid[-1][0] evaluate to, and what happens with grid[2][0]?
Show answer
grid[0][-1] is 3 and grid[-1][0] is 4, so the sum is 7. grid[2][0] raises an IndexError because the grid has only rows 0 and 1.
Exercise
Write one statement that doubles the value in row 1, column 1 of grid.
Show answer
grid[1][1] *= 2