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 lists are mutable, and understand that assigning a list to a second name creates an alias, not a copy.
Reading and changing nested items
Each index step goes one level deeper. The first index picks an inner list, and the second index picks an item inside it.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[1]) # [4, 5, 6]
print(grid[1][2]) # 6
print(grid[-1][0]) # 7
grid[0][0] = 10
print(grid) # [[10, 2, 3], [4, 5, 6], [7, 8, 9]]grid[1] is an ordinary list. Any list method works on it, so grid[1].append(0) changes only that row.
Inner lists do not have to be the same length. A list of rows with different lengths is called a ragged list. Indexing past the end of a short row raises IndexError.
Looping over nested lists
Use one loop for each level. A comprehension can flatten the structure into a single list.
grid = [[1, 2, 3], [4, 5], [6]]
for row in grid:
for value in row:
print(value, end=" ")
print()
flat = [value for row in grid for value in row]
print(flat) # [1, 2, 3, 4, 5, 6]In the comprehension, the for clauses read in the same order as the nested loops: row first, then value.
Building a grid correctly
Multiplying a list repeats references to the same object. For a list of numbers this is harmless, because numbers cannot be changed in place. For a list of lists it creates one row that appears several times.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
print(bad[0] is bad[1]) # True
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]
print(grid[0] is grid[1]) # FalseThe comprehension runs [0] * 3 once for every row, so each row is a new list.
Copying nested lists
list.copy(), list(x) and x[:] all make a shallow copy. The outer list is new, but its items are the same objects. With nested lists, the copy and the original share their inner lists.
import copy
original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = copy.deepcopy(original)
original[0].append(99)
print(shallow) # [[1, 2, 99], [3, 4]]
print(deep) # [[1, 2], [3, 4]]
original.append([5, 6])
print(shallow) # [[1, 2, 99], [3, 4]] (outer list is separate)copy.deepcopy copies every level, so the result shares nothing with the original. Deep copies cost more time and memory. Use one only when you need full independence.
A shallow copy is enough when you only add, remove or reorder rows. You need a deep copy when you will change items inside the rows.
Choosing a structure
| Task | Use |
|---|---|
| Build an n by m grid | `[[0] * m for _ in range(n)]` |
| Flatten one level | `[v for row in grid for v in row]` |
| Copy rows, then replace or reorder them | `grid.copy()` |
| Copy rows, then change items inside them | `copy.deepcopy(grid)` |
Exercise
What does this code print, and why? row = [0, 0] table = [row, row] table[0][1] = 5 print(table) How would you change the first line so that only the first row changes?
Show answer
It prints [[0, 5], [0, 5]]. Both slots of table refer to the same list object, so changing it through table[0] also changes table[1]. Build a separate list for each slot, for example table = [[0, 0] for _ in range(2)] or table = [row, row.copy()].
Exercise
Given data = [[1, 2], [3, 4]] and backup = data.copy(), you run data[1][0] = 30. What is backup, and what one-line change to the way backup is made would keep it at [[1, 2], [3, 4]]?
Show answer
backup is [[1, 2], [30, 4]], because the shallow copy shares the inner lists. Make the backup with backup = copy.deepcopy(data) after import copy.