Loading...
Loading...
Sum or build values inside a loop
The accumulator pattern is one of the most common programming patterns. You start with a variable set to a "neutral" value, then update it as you loop through data. It's used for summing, counting, building strings, and more.
numbers = [10, 20, 30, 40, 50]
total = 0 # Start with 0 (neutral for addition)
for n in numbers:
total = total + n # Add each number to the accumulator
print(total) # 150Let's trace the execution:
numbers = [10, 20, 30, 40, 50]
total = 0| Iteration | `n` | Before `total` | `total = total + n` | After `total` |
|---|---|---|---|---|
| 1st | 10 | 0 | 0 + 10 | 10 |
| 2nd | 20 | 10 | 10 + 20 | 30 |
| 3rd | 30 | 30 | 30 + 30 | 60 |
| 4th | 40 | 60 | 60 + 40 | 100 |
| 5th | 50 | 100 | 100 + 50 | 150 |
The accumulator adds to itself each iteration, growing by one step at a time.
# Counting
count = 0
for item in items:
if item > 0:
count += 1 # Count positive numbers
# Building a string
result = ""
for letter in "hello":
result += letter.upper() + " "
print(result) # "H E L L O "
# Finding a maximum
max_value = float("-inf")
for n in numbers:
if n > max_value:
max_value = n # Keep track of the biggest so farAny time you need to combine or summarize data:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `total = 0` inside the loop | Resets to 0 every iteration — final value is just the last item | Initialize **before** the loop |
| `for n in numbers: total = n` | Overwrites instead of accumulating | `total += n` |
| Forgetting to initialize | Using a variable before assignment = NameError | Always start with `total = 0` |
Create a list grades = [85, 92, 78, 95, 88]. Use the accumulator pattern to:
grades = [85, 92, 78, 95, 88]
total = 0
count = 0
for g in grades:
total += g
if g > 90:
count += 1
print(f"Sum: {total}")
print(f"Above 90: {count}")