Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.

Two positions: the row first, then the column, both from 0.
In code
grid = [[1, 2, 3],
        [4, 5, 6]]
cell = grid[1][2]     # 6

Visit 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.

Outer loop: each row. Inner loop: each number in that row.
In code
total = 0
for row in grid:
    for x in row:
        total = total + x
Adding up a 3 by 3 grid
012
0
3
1
4
1
1
5
9
2
2
6
5
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.

Move 1 of 3