Menu

2D Arrays

Visiting every element in a 2D array

To process every value stored in a 2D array, use nested loops. The outer loop steps through each row, and the inner loop steps through every column in the current row. The inner loop finishes all its columns before the outer loop moves to the next row, so each element is processed exactly once.

If there are r rows and c columns, the body of the inner loop runs r × c times. For example, a grid with 5 rows and 6 columns has 30 elements, so the inner loop body runs 30 times.

Keeping totals

While the nested loops run, you can keep a running total for the current row. Reset that row total to 0 at the start of each new row, before adding to it. You can also add each row total to an overall total, so the whole 2D array is summarised in one pass.

temperatures = [[18, 22, 25, 19], [21, 17, 24, 23], [20, 26, 21, 16]]
overall_hot_days = 0
for city_index in range(len(temperatures)):
    city_hot_days = 0
    for day_index in range(len(temperatures[city_index])):
        if temperatures[city_index][day_index] > 20:
            city_hot_days = city_hot_days + 1
    print("City", city_index + 1, "had", city_hot_days, "hot days")
    overall_hot_days = overall_hot_days + city_hot_days
print("Total hot days:", overall_hot_days)

Output:

City 1 had 2 hot days
City 2 had 3 hot days
City 3 had 2 hot days
Total hot days: 7

The outer loop uses len(temperatures) to visit each city. The inner loop uses len(temperatures[city_index]) to visit every reading in that city. The running total for each city is reset inside the outer loop, before the inner loop runs, so each city's count of hot days starts from 0.

Practise this