Two-dimensional Arrays (2D Lists)
A 2D list in Python is a list whose items are themselves lists. Each inner list is one row, and the outer list holds the rows in order. You create one with nested square brackets: the outer brackets hold the rows, and each row has its own brackets.
relay_teams = [
['Amir', 'Katie', 'Jo', 'Sam'],
['Dev', 'Mia', 'Ibrahim', 'Lucy'],
['Nia', 'Tom', 'Erin', 'Zak']
]
print(relay_teams[1][2])
relay_teams[0][3] = 'Ali'
print(relay_teams[0])
print(relay_teams[0][3])Output:
Ibrahim
['Amir', 'Katie', 'Jo', 'Ali']
Ali
To reach one item, give two indexes in separate square brackets: the row (record) index first, then the column (field) index. The same notation reads a value or assigns a new one, so putting the two indexes before an equals sign replaces that item. Using only the row index returns the whole inner list, which is the whole record rather than one field.
Indexes must be in the correct order. Both indexes count from 0, so the first row and the first field are both at index 0. If you reverse the two indexes, you may read a different item, or Python may raise an IndexError if one index is outside the range of the list. For example, asking for row 3 in a list with rows 0 to 2 fails before the column is used.
A 2D list can be built up inside a loop by creating a row list for each record and appending it to the outer list. Each new row is added at the end, so the rows stay in the order the loop runs.
scores = []
for match in range(3):
home = int(input('Home score: '))
away = int(input('Away score: '))
row = [home, away]
scores.append(row)
print(scores[1][0])Output when the user types 3, 2, 1, 4, 0, 0:
Home score: 3
Away score: 2
Home score: 1
Away score: 4
Home score: 0
Away score: 0
1
A 2D list does not have to be a perfect rectangle. One row may hold three fields and the next only two. Code that assumes every row has the same number of fields, such as always using the third column, can fail with an IndexError on a shorter row. Check each row's length when the layout may vary.
Edexcel GCSE Computer Science · Two-dimensional Arrays (2D Lists)