Computer Science Essentials, Unit 4, Lesson 3 of 5

2D lists and records

GCSE Computer Science, Onscreen programming, 40 minutes

Sign in

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.

  1. Say what one row means and what one column means, such as a week and a day.
  2. Decide which index changes in the inner loop.
  3. Write the cell as grid[row][column], row first.
  4. 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

  1. 2D lists
  2. Searching and counting backwards
  3. Records from a file
  4. 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.

All of Onscreen programming