Sub topic 5
Row Sums and Column Sums
This chapter assumes you can write nested for loops, index a Python list, and read a nested list as a grid with grid[row][column]. If those are new, review the earlier chapters on indexing and traversal first.
Why aggregates matter
An aggregate reduces many values to one. For a grid, the two most common aggregates are the row sum and the column sum. A row sum adds every value in one row. A column sum adds every value in one column. Both appear in spreadsheets (totals per month, totals per product), in image processing, and in matrix algorithms.
For a grid with m rows and n columns, there are m row sums and n column sums. The sums of the rows and the sums of the columns both add up to the same grand total, which gives you a quick correctness check.
Row sums
A row is already a list, so Python's built-in sum works on it directly.
grid = [
[1, 2, 3],
[4, 5, 6],
]
row_sums = [sum(row) for row in grid]
print(row_sums) # [6, 15]The comprehension visits each row once, and sum visits each value in that row once. Every cell is touched exactly one time.
Column sums
A column is not stored as a single list, so you cannot pass it to sum directly. You build each column by fixing the column index c and letting the row index r change.
grid = [
[1, 2, 3],
[4, 5, 6],
]
rows, cols = len(grid), len(grid[0])
col_sums = [sum(grid[r][c] for r in range(rows)) for c in range(cols)]
print(col_sums) # [5, 7, 9]The outer comprehension picks a column. The inner generator walks down that column, one row at a time.
The following diagram shows which cells each kind of sum reads.
Computing both in one pass
The code above reads the grid twice. You can compute both sets of sums in a single traversal by accumulating into two lists.
def aggregates(grid):
rows, cols = len(grid), len(grid[0])
row_sums = [0] * rows
col_sums = [0] * cols
for r in range(rows):
for c in range(cols):
value = grid[r][c]
row_sums[r] += value
col_sums[c] += value
return row_sums, col_sums
grid = [[1, 2, 3], [4, 5, 6]]
row_sums, col_sums = aggregates(grid)
print(row_sums) # [6, 15]
print(col_sums) # [5, 7, 9]
print(sum(row_sums) == sum(col_sums)) # TrueThe last line is the consistency check from earlier. If the two totals differ, one of your loops has a bug.
Here [0] * rows is safe because the elements are integers, which are immutable. The shared-row problem only appears when you repeat a list that contains other lists.
Common errors
- Swapping the bounds. Looping
rup tocolsraises anIndexErroron a non-square grid. Userowsfor the row index andcolsfor the column index. - Using
sum(grid[c])for a column. This adds a row, not a column. It silently returns wrong numbers on square grids. - Reading
len(grid[0])on an empty grid. An empty list has no first row, so this raises anIndexError. Checkif not gridfirst when empty input is possible. - Ragged rows. If rows have different lengths,
grid[r][c]fails for short rows. Either validate the shape or uselen(grid[r])per row.
Cost
Both approaches visit each of the m * n cells once, so the time is O(m * n). The extra space is O(m + n) for the two result lists.
Exercise
For the grid [[2, 4], [6, 8], [10, 12]], what are the row sums and the column sums? What check confirms your answer?
Show answer
The row sums are [6, 14, 22] and the column sums are [18, 24]. Both lists add up to 42, so the totals agree.
Exercise
Write a Python expression that returns the sum of the last column of a non-empty rectangular grid named grid.
Show answer
sum(row[-1] for row in grid). Each row's last element is the entry in the last column, so adding them gives that column's sum.