A grid of numbers
Read a table of numbers, row by row, with a loop inside a loop. About 10 minutes.
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.
grid is [[1, 2], [3, 4]]. What is grid[1][0]?
- A3
- B2
- C4
Show the answer
3. Row 1 is [3, 4], and column 0 of it is 3.
Grid total
You get a grid of numbers as a list of rows. Return the sum of all the numbers in it.
grid = [[3, 1, 4], [1, 5, 9], [2, 6, 5]] → 36
0 ≤ number of rows ≤ 20 · 0 ≤ numbers per row ≤ 20 · −1,000 ≤ each number ≤ 1,000