A list of lists
A spreadsheet is a table: rows going across, and columns going down. In code, a grid is a list whose items are themselves lists. Each inner list is one row.
To reach a single cell you need two positions: the row first, then the column. Both start at 0. In the grid below, row 1 is the list [4, 5, 6], so the cell in row 1 and column 2 is the 6. A grid is the tool for boards, maps, and tables of marks.
grid = [[1, 2, 3],
[4, 5, 6]]
cell = grid[1][2] # 6Visit every cell
To look at every cell, use two loops. The outer loop takes one row at a time, and the inner loop takes each number in that row. This is just like handing out rows of exam papers: you finish a whole row before you start the next.
If you want a total, make the total before both loops, and add each number inside the inner loop. When both loops finish, every cell has been visited exactly once.
total = 0
for row in grid:
for x in row:
total = total + x- row
- 0
- total
- 8
The outer loop takes row 0. The inner loop adds 3, 1 and 4 one by one, and the total reaches 8.