Sub topic 12
Working with nested lists
A nested list is a list that contains other lists. This chapter assumes you can index and slice a list, know that assignment creates an alias rather than a copy, and can write a for loop and a basic list comprehension. It builds on those ideas and shows where they cause trouble once lists hold lists.
What a nested list is
A list can hold any object, including another list. The most common use is a grid (a table of rows and columns), where each inner list is one row.
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
print(len(grid)) # 3 rows
print(len(grid[0])) # 3 items in the first rowPython has no separate "2D array" type here. The outer list stores references to three inner list objects. Every behavior in this chapter follows from that one fact.
Reading and changing items
Each pair of square brackets takes one step. grid[1] gives the second row, and indexing that row gives one item.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[1]) # [4, 5, 6]
print(grid[1][2]) # 6
print(grid[-1][-1]) # 9, last item of the last row
grid[0][0] = 10 # replace one item inside the first row
grid[2] = [0, 0, 0] # replace a whole row
print(grid) # [[10, 2, 3], [4, 5, 6], [0, 0, 0]]Assigning to grid[0][0] changes the inner list. Assigning to grid[2] changes which inner list the outer list points to.
Rows are easy, columns are not
Slicing works on the outer list, so it returns rows, never columns.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[:2]) # [[1, 2, 3], [4, 5, 6]]
print(grid[:2][0]) # [1, 2, 3], still a row
print([row[1] for row in grid]) # [2, 5, 8], the middle columnThe expression grid[:2][0] is a common mistake. It slices first, which gives a new outer list of two rows, and then takes the first row of that result. To get a column, build it with a comprehension.
How nesting looks in memory
The diagram below shows two outer lists. In the first, both slots refer to the same inner list. In the second, each slot has its own inner list.
Changing shared through bad[0] also changes what bad[1] shows, because they are the same object. Changing row0 leaves row1 alone.
Building a grid correctly
You have seen the repetition trap in an earlier chapter. It matters most for nested lists, so here it is again with the fix.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]][0] * 3 is safe because the items are integers, which cannot be changed in place. [[0] * 3] * 2 repeats a reference to one mutable list. The comprehension runs [0] * 3 once per row, so each row is a new list.
A quick check is the is operator, which tests whether two names refer to the same object.
bad = [[0] * 3] * 2
print(bad[0] is bad[1]) # True: one shared row
grid = [[0] * 3 for _ in range(2)]
print(grid[0] is grid[1]) # False: separate rowsLooping over nested lists
Use one loop per level. enumerate gives you the row and column numbers without manual counters.
grid = [[1, 2, 3], [4, 5, 6]]
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value % 2 == 0:
print(f"even value {value} at row {r}, column {c}")This prints the position of 2, 4 and 6. When rows hold fixed-size records, unpack them in the loop header.
students = [["Ana", 91], ["Ben", 85], ["Cy", 91]]
for name, score in students:
print(name, score)If a row has a different length than the pattern expects, unpacking raises ValueError.
Changing rows while looping
Rebinding the loop variable does not change the grid, but mutating the row does.
grid = [[1, 2], [3, 4]]
for row in grid:
row = row + [0] # builds a new list; grid is unchanged
print(grid) # [[1, 2], [3, 4]]
for row in grid:
row.append(0) # changes the inner list in place
print(grid) # [[1, 2, 0], [3, 4, 0]]The same rule applies to assignment: row = ... only moves the name row. To replace the contents of the existing row, use slice assignment: row[:] = [0, 0, 0].
Flattening, transposing and sorting
Three patterns come up often with nested lists.
grid = [[1, 2, 3], [4, 5, 6]]
flat = [v for row in grid for v in row]
print(flat) # [1, 2, 3, 4, 5, 6]
transposed = [list(col) for col in zip(*grid)]
print(transposed) # [[1, 4], [2, 5], [3, 6]]
students = [["Ana", 91], ["Ben", 85], ["Cy", 91]]
ranked = sorted(students, key=lambda s: (-s[1], s[0]))
print(ranked) # [['Ana', 91], ['Cy', 91], ['Ben', 85]]In the flattening comprehension, the for clauses appear in the same order as the nested loops you would write by hand: the row loop first, then the item loop.
zip(*grid) passes each row as a separate argument to zip, which pairs up the first items, then the second items, and so on. The key function in the last example returns a tuple, so Python sorts by score descending and breaks ties by name.
Do not flatten with sum(grid, []). It works, but it builds a new list at every step, so the cost grows quadratically with the number of rows. Use the comprehension above, or itertools.chain.from_iterable(grid).
Copying nested lists
A shallow copy duplicates only the outer list. The inner lists are still shared. A deep copy duplicates every level.
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = copy.deepcopy(original)
original[0].append(99) # change an inner list
print(shallow) # [[1, 2, 99], [3, 4]]
print(deep) # [[1, 2], [3, 4]]
print(shallow[0] is original[0]) # True
original.append([5, 6]) # change the outer list
print(shallow) # [[1, 2, 99], [3, 4]] (no new row)The shallow copy sees the change to the inner list but not the new outer item. This is the usual source of confusion: whether a change shows up depends on which level you modified.
For a grid of numbers or strings, there is a cheaper option than deepcopy. Copy each row once.
grid = [[1, 2], [3, 4]]
snapshot = [row[:] for row in grid]
grid[0][0] = 100
print(snapshot) # [[1, 2], [3, 4]]This copies two levels, which is enough when the items are immutable. If the rows contain further lists or other mutable objects, use copy.deepcopy.
Ragged lists and edge cases
Inner lists do not have to be the same length. Python does not enforce a rectangular shape.
jagged = [[1], [2, 3], [4, 5, 6]]
print([len(row) for row in jagged]) # [1, 2, 3]
print(jagged[2][2]) # 6
# jagged[0][1] raises IndexError: list index out of rangeCode that assumes a rectangle will fail on ragged data. Two cases need care:
zip(*jagged)stops at the shortest row, so it silently drops data.itertools.zip_longestpads shorter rows instead.- An empty outer list has no first row, so
len(grid[0])raisesIndexError. Checkif grid:before reading the width.
Summary of common errors
| Symptom | Cause | Fix |
|---|---|---|
| Changing one row changes all rows | Rows built with `[[0] * n] * m` | Use `[[0] * n for _ in range(m)]` |
| Copy changes when the original changes | Shallow copy shares inner lists | Use `copy.deepcopy` or `[row[:] for row in grid]` |
| `grid[:2][0]` returns a row, not a column | Slicing acts on the outer list | Use `[row[i] for row in grid]` |
| Loop assignment has no effect | `row = ...` rebinds only the name | Mutate the row, or use `row[:] = ...` |
| `IndexError` on some rows | Rows have different lengths | Check lengths, or use `zip_longest` |
Exercise
What does this code print, and why? bad = [[0] 2] 3 bad[1][1] = 5 print(bad)
Show answer
It prints [[0, 5], [0, 5], [0, 5]]. The outer list holds three references to the same inner list, so setting bad[1][1] changes the one shared row, and all three positions show the change. Building the grid with [[0] * 2 for _ in range(3)] creates three separate rows, and then only bad[1] would change.
Exercise
Given grid = [[1, 2], [3, 4]], write code that makes a copy named backup, then sets grid[0][0] to 100 without changing backup. Show the value of backup afterwards.
Show answer
backup = [row[:] for row in grid] (or import copy and use copy.deepcopy(grid)). Then grid[0][0] = 100 leaves backup as [[1, 2], [3, 4]]. Using backup = grid.copy() would fail the test, because it is a shallow copy and backup[0] would still be the same list as grid[0], so backup would show 100.