Sub topic 1
What a 2D Array Is: Rows, Columns, and Shape
Prerequisites
This chapter assumes you know:
- Basic Python syntax: variables, loops, and functions.
- One-dimensional lists and zero-based indexing.
- Nested
forloops, which later chapters use heavily. - The idea of a table of numbers, such as a spreadsheet.
The model
A two-dimensional (2D) array stores values in a table. Each value sits in a cell. You find a cell with two indices: first the row, then the column. Both start at 0.
The size of the table is its shape, written m by n. Here m is the number of rows and n is the number of columns. A 2 by 3 array has 2 rows, 3 columns, and 2 × 3 = 6 cells.
A matrix is a 2D array of numbers, used with operations such as addition and multiplication. A grid is a 2D array used as a map or board. The storage is the same in both cases.
Building one in Python
Python has no built-in 2D array type. The usual substitute is a list of lists. The outer list holds the rows, and each inner list is one 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]]Read grid[1][2] from left to right. grid[1] is the whole second row, [4, 5, 6]. Then [2] picks the third item of that row. The first index is always the row.
Reading the shape
The shape comes from two len calls. These expressions assume the array is not empty.
| Expression | Meaning | Value for the example |
|---|---|---|
| `len(grid)` | Number of rows (m) | 2 |
| `len(grid[0])` | Number of columns (n) | 3 |
| `len(grid) * len(grid[0])` | Number of cells | 6 |
| `grid[m - 1][n - 1]` | Last cell | 6 |
The valid row indices run from 0 to m - 1. The valid column indices run from 0 to n - 1. Any other index raises an IndexError, except negative indices. Those silently count from the end, which can hide bugs.
Python does not enforce a shape. A list of lists is only a true rectangle if every row has the same length. This helper checks that and returns the shape:
def shape(grid):
rows = len(grid)
cols = len(grid[0]) if rows else 0
if any(len(row) != cols for row in grid):
raise ValueError("rows have different lengths")
return rows, cols
print(shape([[1, 2, 3], [4, 5, 6]])) # (2, 3)
print(shape([])) # (0, 0)Rows of unequal length are legal in Python. They are called jagged arrays and get their own chapter.
Common errors
- Swapping the indices. Writing
grid[col][row]compiles and runs on a square grid, but gives wrong results or anIndexErroron a non-square one. Name your variablesrandcand keep that order. - Reading
len(grid[0])on an empty list.[]has no row 0, so this raises anIndexError. Checklen(grid)first, asshapedoes. - Confusing m by n with x and y. In a picture, x is horizontal, which is the column. In code, the row index comes first, so
grid[y][x]is the correct order.
Exercise
What is the shape of data = [[7, 8], [9, 10], [11, 12], [13, 14]], and what does data[2][1] return?
Show answer
The shape is 4 by 2, because there are 4 rows and each row has 2 columns. data[2] is the third row, [11, 12], so data[2][1] is 12.
Exercise
A 2D array has shape 5 by 8. What is the largest valid row index, the largest valid column index, and the number of cells?
Show answer
The largest row index is 4, the largest column index is 7, and there are 5 × 8 = 40 cells.