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.
What you will learn
- Complete nested loops over a 2D list of any size
- Find an item in a grid and return its row and column
- Turn file lines into records and records into file lines
- Select, total, sort and report on a list of records
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 locked.
In this lesson
- 2D lists
- Searching and counting backwards
- Records from a file
- Try it: Totals in a grid
11 practice questions, marked as you go; about 40 minutes in all.
Key terms
Fields
In this unit: Onscreen programming
Partly written Python programs to complete, amend, fix and extend, checked by running them against tests: subroutines, 2D lists, records from files, validation, strings and longer tasks in parts.