Common 2D Array Operations
You'll learn how to perform useful calculations on 2D arrays, like summing rows or columns, finding extremes, and flipping the matrix.
Now that you can navigate 2D arrays, it's time to do useful work with them. Think of a 2D array as a spreadsheet: you might want to total a row (like summing sales per quarter), find the highest value in a column (like the best test score), or flip rows and columns (transpose).
Summing Rows and Columns
To sum a row, fix the first index and iterate through the second:
# Sum row 0
total = 0
for col in range(len(grid[0])):
total += grid[0][col]
To sum a column, fix the second index and iterate through the first:
# Sum column 1
total = 0
for row in range(len(grid)):
total += grid[row][1]
Finding Max/Min Values
Loop through all elements, tracking the largest or smallest seen so far:
max_value = grid[0][0] # Start with first element
for row in range(len(grid)):
for col in range(len(grid[row])):
if grid[row][col] > max_value:
max_value = grid[row][col]
Matrix Transposition
Transposition swaps rows and columns—row 0 becomes column 0. Create a new array where result[col][row] = original[row][col]:
# Assuming 3x2 grid becomes 2x3 transposed
transposed = [[0, 0, 0], [0, 0, 0]]
for row in range(len(grid)):
for col in range(len(grid[row])):
transposed[col][row] = grid[row][col]
Key Takeaway: Common 2D array operations use nested loops with careful index control—sum rows by iterating columns at a fixed row, sum columns by iterating rows at a fixed column, and transpose by swapping indices when copying.