2D lists and records
Working through a 2D list with nested loops, finding and placing items in a grid, fixing swapped indexes, and lists of records read from a file: selecting, totalling, sorting, reporting and getting them ready to write back.
2D lists
A 2D list is a list of lists: a grid. grid[r][c] is row r, column c, both counted from 0. The number of rows is len(grid) and the number of columns is len(grid[0]).
for r in range(len(grid)):
for c in range(len(grid[r])):
print(grid[r][c])
The outer loop picks a row and the inner loop visits each cell in it. Use the lengths, never fixed numbers, so the code works for a grid of any size.
- Say what one row means and what one column means, such as a week and a day.
- Decide which index changes in the inner loop.
- Write the cell as grid[row][column], row first.
- Test with a grid that is not square: a swapped index shows up at once.
The rest of this lesson and its 11 practice questions are in Plus.
Screen 1 of 4, free to read.
- 11 exam-style questions, marked as you go, each with a worked solution
- Anything you get wrong is saved to your flashcards