6.3.1 – Records and two-dimensional lists

6.3.1 – Records and two-dimensional lists

Represent related fields as records, select and update values with two indexes, and process rectangular tables without confusing rows with fields.

Choose fields and types

A record stores fields about one entity. A library book might need a code, title, number of copies and availability flag. The fields have different jobs, so document their order and choose a type for each.

IndexFieldTypeExample
0codestringB17
1titlestringRivers
2copiesinteger4
3availableBooleanTrue
Python
book = ["B17", "Rivers", 4, True]

The PLS represents records with Python lists. The code remains text even if it contains digits; the count is an integer because arithmetic is needed. A record usually mixes types, but it need not: ["B17", "Rivers"] can still represent two different fields of one book. Purpose distinguishes it from an array of same-type items with a shared meaning, such as a list of copy counts.

A string is one sequence of characters. A one-dimensional array or record uses one index to reach an item. A single record does not become two-dimensional merely because it contains several fields.

Choose a record when the fields must stay associated. Separate arrays of codes, titles and copies can become misaligned if one array is reordered without the others.

Row first, then field

A two-dimensional list contains inner lists. The first index selects a row; the second selects an item in that row. Both start at zero.

Python
stock = [
    ["A14", "USB hub", 8],
    ["B07", "Mouse", 15],
    ["C21", "Keyboard", 6]
]
print(stock[2])
print(stock[2][1])
stock[0][2] = 10
print(stock[0][2])

Each row is a record in the order [code, name, quantity]. The output is:

Output
['C21', 'Keyboard', 6]
Keyboard
10

stock[2] is the complete third record; stock[2][1] is its name field. Replacing field 2 changes a quantity without adding a field. len(stock) is the number of records, whereas len(stock[0]) is the number of fields in the first record.

PLS tables are rectangular: every row has the same number of fields in the same order. Do not append a fourth field to just one three-field record. A table of scores can instead be a two-dimensional array where every cell is an integer:

Python
scores = [[12, 15, 11], [9, 14, 13]]
print(scores[1][2])

This prints 13: row index 1, then column index 2. For two rows of three cells, valid non-negative row indexes are 0–1 and column indexes 0–2. Checking or knowing bounds prevents an IndexError.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account