Start at 0
Accumulator
Zero is the additive identity.
Summing an array means visiting every element once and adding it to a running total (the accumulator pattern). Example: [1, 2, 3, 4, 5] → 15. Empty lists sum to 0; negatives are allowed. This tutorial covers a manual loop, user input, a live preview, worked Python examples, edge cases, and complexity.
Accumulator
Zero is the additive identity.
total += x
Visit each element exactly once.
Edge case
No elements means the total stays 0.
Same loop
They simply reduce the total.
Try 1,2,3,4,5
Compute a custom list instantly.
Interview tip
Show the loop; use sum() later.
Summing an array is the simplest one-pass list problem: keep a running total and add every value. With [1, 2, 3, 4, 5] the total climbs 0 → 1 → 3 → 6 → 10 → 15.
Interviews want the manual accumulator so you prove you understand traversal. In real Python you can later switch to built-in sum(arr) without changing the idea.
It is the foundation for averages, prefix sums, and many later array scans (max, min, product).
total starts at 0.
O(n) time, O(1) space.
Natural with this pattern.
Same scan, different keep.
In short: total = 0, then total += value for every element.
Given a list of integers, return the sum of all elements.
# [1, 2, 3, 4, 5] -> 15
# [10, -2, 7] -> 15
# [] -> 0 | Item | Type | Description |
|---|---|---|
arr | list[int] | Values to add (may be empty). |
| Return | int | Sum of all elements (0 if empty). |
total | int | Running accumulator. |
function array_sum(arr):
total = 0
for value in arr:
total += value
return total | Method | Idea | Notes |
|---|---|---|
| Manual loop | total += value | Interview default |
| Built-in sum() | sum(arr) | Best in production |
| Index loop | for i in range(len(arr)) | Same O(n); useful with indices |
| Goal | Pattern |
|---|---|
| Init | total = 0 |
| Add | total += value |
| For-each | for value in arr: |
| By index | for i in range(len(arr)): total += arr[i] |
| Built-in | sum(arr) |
| Empty | [] → 0 |
Same result — different packaging.
total += xClearest interview answer
sum(arr)Idiomatic production Python
arr[i]When you also need positions
keep bestSame pass, different update
Reach for an array sum whenever you need a one-pass total.
First array traversal after variables.
Sum then divide by length.
Running totals unlock range queries.
Read n values, then total them.
Product starts at 1, not 0.
Key benefit: one pattern — start at 0, add everything — that transfers to almost every array scan.
Enter integers separated by commas or spaces and compute the sum instantly.
Three complete Python programs — sum a fixed list, read user input, and show a running total with negatives. Click View Output to reveal sample console results.
The classic accumulator on a hard-coded list.
Classic example: [1, 2, 3, 4, 5] → 15.
def sum_array(arr: list[int]) -> int:
total = 0
for value in arr:
total += value
return total
array = [1, 2, 3, 4, 5]
print(f"Sum of the array elements: {sum_array(array)}") total starts at 0 and climbs as each value is added: 1, then 3, 6, 10, and finally 15.
Same helper, values come from the user.
Reads n and then n numbers from the user. Rejects a negative length.
def sum_array(arr: list[int]) -> int:
total = 0
for value in arr:
total += value
return total
n = int(input("Enter number of elements: ").strip())
if n < 0:
raise ValueError("n must be nonnegative.")
arr = []
for i in range(n):
arr.append(int(input(f"Enter element {i + 1}: ").strip()))
print(f"Sum of the array elements: {sum_array(arr)}") Build the list first, then reuse the same sum_array helper. Keeping input and summing separate makes testing easier.
Print the accumulator after each step so you can see negatives reduce the total.
arr = [10, -2, 7]
total = 0
print("Running total:")
for value in arr:
total += value
print(f" after {value:+d}: {total}")
print(f"Final sum: {total}") Negatives are not special-cased — addition handles them. Tracing the running total is a great whiteboard habit.
Additive identity for an empty start.
for value in arr
Fold the next element into the sum.
After the loop, total is the answer.
Watch the accumulator climb from 0 to 15.
| Step | value | total after |
|---|---|---|
| start | — | 0 |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
Same table works for [10, -2, 7]: 0 → 10 → 8 → 15.
Where array sums show up beyond the interview prompt.
First array traversal drill.
Example: sum_array([1,2,3]).
Sum then divide by n.
Example: average tutorials.
Cart totals, scores, balances.
Example: add line items.
Store running totals for ranges.
Example: range queries.
Checksum-style quick totals.
Example: live preview.
Same pass, keep the best.
Example: related CTA.
Pro Tip: say “accumulator starts at zero” before you write the loop.
Why the one-pass accumulator is the right first approach.
One variable, one loop, one update.
You must look at every element anyway.
Only the accumulator — O(1) space.
Empty lists and negatives need no special cases.
Pro Tip: mention sum(arr) as a production shortcut after you show the manual loop.
Small habits that keep sum solutions interview-ready.
Never seed with arr[0] for summing.
Do not nest or sort first.
Guard negative n when reading length.
Write the running total for small lists.
Mention it after the manual solution.
Pro Tip: sanity-check [], [1,2,3,4,5], and [10,-2,7] — if those three work, you are solid.
Mistakes that commonly break sum-of-array programs.
That pattern is for max/min, not sum.
→ Always start sum at 0.
Crashing when n = 0.
→ Empty sum is 0 with this pattern.
Treating them as invalid.
→ Addition already handles them.
Unnecessary O(n log n) work.
→ One linear pass is enough.
Unvalidated input breaks int conversion.
→ Validate before summing.
Handle these before claiming the sum is complete.
Result remains 0.
They reduce the total naturally.
[7] → 7.
Handle non-numeric values before summing.
Raise or re-prompt.
Adding 0 leaves total unchanged.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
sum(arr) is fine after you can write the loop.Quick Takeaway: total = 0; for each value, total += value.
| Approach | Time | Extra space |
|---|---|---|
| Single pass | O(n) | O(1) |
| Built-in sum() | O(n) | O(1) |
| Sort then add | O(n log n) | varies |
You must read every element, so linear time is optimal for an unsorted list.
Summing an array is the accumulator pattern: start at 0, add every element once, return the total. Empty lists stay 0; negatives just subtract.
Practice the three examples above, then continue to finding the maximum of an array.
total = 0; total += each value.
Master the accumulator pattern for every later scan.
total = 0
Inittotal += x
Loopsum is 0
Edgejust subtract
InputO(n) / O(1)
AnalysisThe sum-of-array problem is a classic accumulator pattern: start with sum = 0, then add each element exactly once.
Learn how to find the largest element with a single linear scan.
9 people found this page helpful