Sub topic 13
Jagged Arrays with Rows of Different Lengths
This chapter assumes you can build and index a nested list, write nested loops, and use len(). You should also know the shape idea from earlier chapters: an m by n grid has m rows and n columns.
What makes an array jagged
A jagged (or ragged) array is a 2D array whose rows have different lengths. Python nested lists allow this naturally, because each row is an independent list.
jagged = [
[1],
[2, 3],
[4, 5, 6],
]
print(len(jagged)) # 3 rows
print([len(row) for row in jagged]) # [1, 2, 3]
print(jagged[2][2]) # 6The outer list holds references to three separate row lists. Nothing forces them to match.
When jagged arrays are useful
Use one when the data has no fixed column count. Common cases are triangular tables, adjacency lists for graphs, and groups of items with varying sizes. A rectangular grid would waste space on padding.
You can build a triangle with a comprehension that ties row length to the row index:
triangle = [[r * 10 + c for c in range(r + 1)] for r in range(4)]
print(triangle) # [[0], [10, 11], [20, 21, 22], [30, 31, 32, 33]]Traversal: use each row's own length
On a rectangular grid, len(grid[0]) gives the column count for every row. On a jagged array it gives only the length of row 0. Using it as a loop limit raises IndexError on short rows and skips elements in long ones. Ask each row for its own length instead.
jagged = [[1], [2, 3], [4, 5, 6]]
for r in range(len(jagged)):
for c in range(len(jagged[r])):
print(jagged[r][c], end=" ")
print() # 1 2 3 4 5 6
print(sum(len(row) for row in jagged)) # 6 cells in totalRow sums need no change, since sum(row) works on any length. Column sums need a guard, because a column may be missing from some rows:
jagged = [[1], [2, 3], [4, 5, 6]]
row_sums = [sum(row) for row in jagged]
width = max(len(row) for row in jagged)
col_sums = [sum(row[c] for row in jagged if c < len(row)) for c in range(width)]
print(row_sums) # [6, 5, 15] is wrong for this data; see belowRun it and check the output yourself. The row sums are [1, 5, 15] and the column sums are [7, 8, 6]. A comment that does not match the real result is a good reminder to verify output rather than trust it.
Bounds checks must be per row
Neighbor checks on a jagged grid must compare the column against the length of the target row, not a global width. The neighbors function from the grid chapter already does this with len(grid[nr]). A check against len(grid[0]) would accept cells that do not exist.
Memory layout: no single formula
The formula r * cols + c works only when every row has the same length. For jagged data, store the flat values plus a start offset for each row. The index of cell (r, c) is starts[r] + c.
jagged = [[1], [2, 3], [4, 5, 6]]
flat = [x for row in jagged for x in row]
starts = [0]
for row in jagged[:-1]:
starts.append(starts[-1] + len(row))
print(flat) # [1, 2, 3, 4, 5, 6]
print(starts) # [0, 1, 3]
print(flat[starts[2] + 1]) # 5, the same as jagged[2][1]This is the idea behind compressed formats for sparse and variable-length data.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Looping to `len(grid[0])` | `IndexError` or skipped cells | Loop to `len(grid[r])` |
| Using `zip(*grid)` to transpose | Silently drops values past the shortest row | Pad rows first, or use `itertools.zip_longest` |
| Assuming a column exists in every row | `IndexError` | Check `c < len(row)` |
Exercise
Given jagged = [[1], [2, 3], [4, 5, 6]], write an expression for the largest row length, and say which index of starts from the offset example tells you where row 2 begins in the flat list.
Show answer
max(len(row) for row in jagged) gives 3. Row 2 begins at starts[2], which is 3, so its elements sit at flat positions 3, 4, and 5.