Totalling a 2D array

Sum the whole grid, or build a list of sums — one total per row, or one total per column.

Programming Beginner 2D arrays · Accumulators ~7 min
The idea

One total — or a total for each line

A single accumulator can sum the entire matrix. To get every row total (or every column total), reset the accumulator for each line and store the result in a list.

TipRow-wise: outer loop is rows, reset total, then append. Column-wise: outer loop is columns.
IdeaAccumulate
row_sums.pyPython
row_sums = []
for r in range(rows):
    total = 0
    for c in range(cols):
        total = total + grid[r][c]
    row_sums.append(total)
Interactive

Run the simulation

Blue cell is being added. Green cells already contributed. The tray holds finished row or column sums.

Step 0 / 0
demo.pyPython
Matrix + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

2D totalling essentials

Whole grid vs a list of line totals.

All

One running total

Nested loops visit every cell; a single total holds the grand sum.

Rows

Reset per row, then append

row_sums ends up with one entry for each row of the grid.

Columns

Same idea, swap axes

Outer loop over columns; col_sums stores each column total.