Menu

Two-dimensional Arrays (2D Lists)

Displaying a 2D List

A 2D list stores rows of related fields, and a nested loop can display every value in it: the outer loop visits each row and the inner loop visits each field in that row. Printing the values on their own is not enough, though. The user looking at the screen cannot see your list, so they have no way of knowing which number is the age and which is the score. Labelled output fixes this: each value is printed next to a word saying what it means.

Why labels matter

In a table of records, the column position fixes the meaning of a field: column 0 might be a name, column 1 an age and column 2 whether the member has paid. When you print the raw values, that ordering is invisible, and it becomes even harder to follow when a row mixes types, such as a string, an integer and a Boolean. Printing Name: before the value makes the output readable on its own.

A worked example

Suppose a school shop stores its stock as a 2D list, one row per item. A heading is printed once, before any loop, to name the table. Then, for each row, the inner loop prints each field beside its own label, joining the label to the value with the text + operator and converting the value with str(). The labels sit in a second list, so the same label is reused for the same column in every row.

stock = [['Pens', 24, False], ['Notebooks', 15, True], ['Calculators', 8, False]]
labels = ['Item', 'Quantity', 'Reduced']

print('School shop stock')
for row in stock:
    position = 0
    for field in row:
        print(labels[position] + ': ' + str(field))
        position = position + 1
    print('---')

Output:

School shop stock
Item: Pens
Quantity: 24
Reduced: False
---
Item: Notebooks
Quantity: 15
Reduced: True
---
Item: Calculators
Quantity: 8
Reduced: False
---

Because the labels sit inside the inner loop, every row produces the same three labelled lines in the same order, so the layout stays consistent from row to row. If a fourth row were appended to the list, the same code would label it too, with no changes needed.

Labelling without a second loop

When the field order is fixed and you only need one line per row, you can label each column directly inside the outer loop. The loop still visits every record; the labels do the explaining.

clubs = [['Chess', 14, 'Room 2'], ['Robotics', 9, 'Hall'], ['Drama', 21, 'Stage']]

print('Club enrolment')
for club in clubs:
    print('Club: ' + club[0] + ' | Members: ' + str(club[1]) + ' | Venue: ' + club[2])

Output:

Club enrolment
Club: Chess | Members: 14 | Venue: Room 2
Club: Robotics | Members: 9 | Venue: Hall
Club: Drama | Members: 21 | Venue: Stage

Practise this