Counting in a 2D array

Count a target across the whole grid, or build a list of counts — one per row, or one per column.

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

One count — or a count for each line

A single count can scan the whole matrix. To get every row count (or every column count), reset the counter for each line and append the result to a list.

TipGreen cells are matches. Blue is the cell being checked right now.
IdeaCount matches
row_counts.pyPython
row_counts = []
for r in range(rows):
    count = 0
    for c in range(cols):
        if grid[r][c] == target:
            count = count + 1
    row_counts.append(count)

Target: 2 · Demo grid has four matches overall.

Interactive

Run the simulation

Watch count rise only on matches. The tray holds finished row or column counts.

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

2D counting essentials

Whole grid vs a list of line counts.

All

One running count

Nested loops visit every cell; a single count holds the total matches.

Rows

Reset per row, then append

row_counts ends up with one entry for each row.

Columns

Same idea, swap axes

Outer loop over columns; col_counts stores each column count.