Nested lists and grids
Read and visit the cells of a grid held as a list of lists, and build one whose rows are separate lists.
It opens on
On this grid, rows run down and columns run across, both counted from 0. Is grid[1][2] the 4 or the 0?
Why it matters
Tables, game boards, images and spreadsheets are grids, and a list of lists is how a first course holds one; the shortcut [[0] * 3] * 3 looks right and builds a grid whose rows are one list.
Good to know first
- Lists: indexing and mutation: items are read and changed by index
- Nested loops: the inner body runs rows times columns times
- Aliasing and mutability: a list that two names share changes for both
Step by step
A list of rows
Read and change a cell of a list of lists with grid[r][c], and give the number of rows and columns from len.
The program builds it as a list of three lists. len(grid) is 3, the number of rows, and len(grid[0]) is 4, the number of items in row 0, which is the number of columns.
the program
A common mix-up
Grid[1][2] is column 1, row 2.
In fact: The first index chooses the row, the second the column.
Visit every cell
Use nested loops to total a grid and to total each column, and say how many times the inner body runs.
The outer loop makes row each of the three lists in turn, and the inner loop makes x each of its four items, so total = total + x runs 3 times 4, which is 12 times, and prints 53. The rows add up to 18, 22 and 13. In general the inner body runs rows times columns times, so the work is O(rows × columns).
A common mix-up
The inner loop runs only once, since it is written once.
In fact: It starts again on every pass of the outer loop, so it runs rows times columns times in all.
The trap of one row repeated
Explain why [[0] * 3] * 3 gives three names for one row, and build a grid whose rows are separate lists.
Inside, [0] * 3 builds one list [0, 0, 0]. The second * 3 repeats the outer list's item three times, but it repeats the arrow, not the list, as b = a did, so the grid holds three arrows to one row.
three rows, one list
A common mix-up
[[0] * 3] * 3 makes three separate rows.
In fact: It makes one row and three arrows to it.
Try it
For g = [[1, 2], [3, 4]], what are g[1][0] and len(g)?Answer
3 and 2
Hint: Row 1 is [3, 4]
How many times does the inner body run for a grid of 5 rows and 6 columns?Answer
30
Hint: Rows times columns
What does print(rows) show after rows = [[0] * 2] * 2 and rows[1][1] = 4?Answer
[[0, 4], [0, 4]]
Hint: Both rows are one list
What is grid[0][3] + grid[2][0]?Answer
11, since grid[0][3] is 6 and grid[2][0] is 5.
What is the sum of column 2?Answer
11, since grid[0][2], grid[1][2] and grid[2][2] are 1, 4 and 6.
