Find Sum of Array in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Arrays

What You’ll Learn

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.

Start at 0

Accumulator

Zero is the additive identity.

One Pass

total += x

Visit each element exactly once.

Empty = 0

Edge case

No elements means the total stays 0.

Negatives OK

Same loop

They simply reduce the total.

Live Preview

Try 1,2,3,4,5

Compute a custom list instantly.

Loop vs sum()

Interview tip

Show the loop; use sum() later.

Introduction

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.

Why it matters?

It is the foundation for averages, prefix sums, and many later array scans (max, min, product).

Key Highlights

Accumulator

total starts at 0.

Single Pass

O(n) time, O(1) space.

Empty = 0

Natural with this pattern.

Next: Max

Same scan, different keep.

In short: total = 0, then total += value for every element.

📝 Problem & Approach

Given a list of integers, return the sum of all elements.

python
# [1, 2, 3, 4, 5] -> 15
# [10, -2, 7]     -> 15
# []              -> 0

Inputs & Outputs

ItemTypeDescription
arrlist[int]Values to add (may be empty).
ReturnintSum of all elements (0 if empty).
totalintRunning accumulator.

Minimal workflow

Pseudocode
function array_sum(arr):
    total = 0
    for value in arr:
        total += value
    return total

Method comparison

MethodIdeaNotes
Manual looptotal += valueInterview default
Built-in sum()sum(arr)Best in production
Index loopfor i in range(len(arr))Same O(n); useful with indices

⚡ Quick Reference

GoalPattern
Inittotal = 0
Addtotal += value
For-eachfor value in arr:
By indexfor i in range(len(arr)): total += arr[i]
Built-insum(arr)
Empty[]0

📋 Loop vs sum() vs Index

Same result — different packaging.

Accumulator
total += x

Clearest interview answer

Built-in
sum(arr)

Idiomatic production Python

Index
arr[i]

When you also need positions

vs max
keep best

Same pass, different update

Context

When This Problem Shows Up

Reach for an array sum whenever you need a one-pass total.

  1. Interview warm-ups

    First array traversal after variables.

  2. Averages

    Sum then divide by length.

  3. Prefix sums

    Running totals unlock range queries.

  4. Input parsing

    Read n values, then total them.

  5. Not for products

    Product starts at 1, not 0.

Key benefit: one pattern — start at 0, add everything — that transfers to almost every array scan.

🔮 Live Preview

Enter integers separated by commas or spaces and compute the sum instantly.

Integers only (safe integer range), up to 2000 values. Empty input sums to 0.

Live result
Press “Compute sum”.

Examples Gallery

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.

📚 Getting Started

The classic accumulator on a hard-coded list.

Example 1 — Sum of a Fixed Array

Classic example: [1, 2, 3, 4, 5] → 15.

python
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)}")

How It Works

total starts at 0 and climbs as each value is added: 1, then 3, 6, 10, and finally 15.

⚡ Reading Input

Same helper, values come from the user.

Example 2 — Sum of an Array (User Input)

Reads n and then n numbers from the user. Rejects a negative length.

python
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)}")

How It Works

Build the list first, then reuse the same sum_array helper. Keeping input and summing separate makes testing easier.

Example 3 — Running Total with Negatives

Print the accumulator after each step so you can see negatives reduce the total.

python
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}")

How It Works

Negatives are not special-cased — addition handles them. Tracing the running total is a great whiteboard habit.

🧠 How the Algorithm Adds

1

Set total = 0

Additive identity for an empty start.

Init
2

Visit each value

for value in arr

Loop
3

total += value

Fold the next element into the sum.

Update
=

Return total

After the loop, total is the answer.

🔎 Worked Walkthrough — [1, 2, 3, 4, 5]

Watch the accumulator climb from 0 to 15.

Stepvaluetotal after
start0
111
223
336
4410
5515

Same table works for [10, -2, 7]: 0 → 10 → 8 → 15.

Use Cases

Where array sums show up beyond the interview prompt.

1. Interview Basics

First array traversal drill.

Example: sum_array([1,2,3]).

2. Averages

Sum then divide by n.

Example: average tutorials.

3. Totals in Apps

Cart totals, scores, balances.

Example: add line items.

4. Prefix Sums

Store running totals for ranges.

Example: range queries.

5. Validation

Checksum-style quick totals.

Example: live preview.

6. Next: Maximum

Same pass, keep the best.

Example: related CTA.

Pro Tip: say “accumulator starts at zero” before you write the loop.

Advantages

Why the one-pass accumulator is the right first approach.

  1. 1. Simple to Explain

    One variable, one loop, one update.

  2. 2. Optimal for Unsorted Lists

    You must look at every element anyway.

  3. 3. Tiny Extra Memory

    Only the accumulator — O(1) space.

  4. 4. Handles Edges Naturally

    Empty lists and negatives need no special cases.

Pro Tip: mention sum(arr) as a production shortcut after you show the manual loop.

Usage Tips

Small habits that keep sum solutions interview-ready.

  1. 1. Start at Zero

    Never seed with arr[0] for summing.

  2. 2. One Loop Only

    Do not nest or sort first.

  3. 3. Validate Input

    Guard negative n when reading length.

  4. 4. Trace on Paper

    Write the running total for small lists.

  5. 5. Know sum()

    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.

Common Pitfalls

Mistakes that commonly break sum-of-array programs.

  1. 1. Starting total at arr[0]

    That pattern is for max/min, not sum.

    → Always start sum at 0.

  2. 2. Skipping Empty Lists

    Crashing when n = 0.

    → Empty sum is 0 with this pattern.

  3. 3. Rejecting Negatives

    Treating them as invalid.

    → Addition already handles them.

  4. 4. Sorting First

    Unnecessary O(n log n) work.

    → One linear pass is enough.

  5. 5. Mixing Strings

    Unvalidated input breaks int conversion.

    → Validate before summing.

Edge Cases

Handle these before claiming the sum is complete.

Empty list

Sum = 0

Result remains 0.

Negatives

Valid input

They reduce the total naturally.

Single element

Sum = that value

[7] → 7.

Invalid input

Validate safely

Handle non-numeric values before summing.

n < 0

Reject length

Raise or re-prompt.

Zeros

No change

Adding 0 leaves total unchanged.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Additive identity. Starting at 0 is what makes empty lists work.
  • Must see every element. You cannot skip values in an unsorted list.
  • Order does not matter. Integer addition is commutative.
  • Product is different. Products start at 1, not 0.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Sum [1..5]

  • Reproduce Example 1
  • Expect 15

2. Trace [10,-2,7]

  • Show running totals
  • Match Example 3

3. Empty list

  • Confirm sum = 0
  • No special branch needed

4. Average follow-up

  • Sum then / len(arr)
  • Guard empty length

Notes

  • Pattern: accumulator starts at 0, then add each element once.
  • Complexity: O(n) time and O(1) extra space.
  • Production: sum(arr) is fine after you can write the loop.
  • Next skill: keep a running maximum or minimum with the same one-pass shape.

Quick Takeaway: total = 0; for each value, total += value.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Single passO(n)O(1)
Built-in sum()O(n)O(1)
Sort then addO(n log n)varies

You must read every element, so linear time is optimal for an unsorted list.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • Start total at 0
  • Visit every element once
  • Allow negatives
  • Treat empty as 0
  • Mention sum() after the loop

❌ Don’t

  • Seed total with arr[0]
  • Sort just to sum
  • Crash on empty lists
  • Skip input validation
  • Confuse with product (starts at 1)

Key Takeaways

Knowledge Unlocked

Five things to remember about summing arrays

Master the accumulator pattern for every later scan.

5
Core concepts
+ 02

Add

total += x

Loop
[] 03

Empty

sum is 0

Edge
- 04

Negatives

just subtract

Input
O 05

Cost

O(n) / O(1)

Analysis

❓ Frequently Asked Questions

Set total = 0, then loop through the list and do total += value for each element.
Zero is the additive identity, so the final total equals the sum of all values.
Yes. The same loop works; negative numbers reduce the total.
Use sum(arr) in production code. Use loops in interviews to show understanding.
O(n) time and O(1) extra space.
By the accumulator pattern, the answer is 0.
No. Addition is associative and commutative for ordinary integers.
Say accumulator out loud, start at 0, then walk every element once.

Did you Know? 🔊

The sum-of-array problem is a classic accumulator pattern: start with sum = 0, then add each element exactly once.

Continue to Maximum of an Array

Learn how to find the largest element with a single linear scan.

Maximum of an array tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful