Level 1
0 / 100 XP

Totals and counters

You often need to add up the numbers in a list, or count how many items meet some test. Both use the same trick: a variable that starts at zero and grows as the loop runs. This is the accumulator pattern.

Summing with a running total

Start a total at 0, then add each item to it inside the loop:

Python
scores = [88, 92, 75] total = 0 for score in scores: total = total + score print(total) # 255

Walk through it:

  • Before the loop, total is 0
  • Pass 1: total = 0 + 88 -> 88
  • Pass 2: total = 88 + 92 -> 180
  • Pass 3: total = 180 + 75 -> 255

The variable accumulates the result one item at a time. Starting at 0 matters — it's the correct starting point for addition.

A shortcut: +=

total = total + score is so common that Python gives you a shorthand, +=:

Python
scores = [88, 92, 75] total = 0 for score in scores: total += score # same as total = total + score print(total) # 255

Both do exactly the same thing. Use whichever is clearer to you.

Counting with a counter

To count how many items pass a test, start a counter at 0 and add 1 each time the test is true:

Python
scores = [88, 92, 75, 60] passing = 0 for score in scores: if score >= 70: passing += 1 print(passing) # 3

Only 88, 92, and 75 are 70 or above, so the counter ends at 3.

Averaging combines both ideas

An average is just a total divided by a count:

Python
scores = [88, 92, 75] total = 0 for score in scores: total += score average = total / len(scores) print(average) # 85.0

Key takeaways

  • The accumulator pattern uses a variable that starts at 0 and grows inside a loop
  • Sum: add each item — total += item
  • Count: add 1 when a condition is true — count += 1
  • += is shorthand for "add to the existing value"
  • Average = total ÷ len(list)