Find Sum of Array in Python
What you'll learn
- The accumulator pattern (
total += value). - How to sum a fixed list and user-provided input.
- How to handle edge cases and complexity discussion in interviews.
Overview
To find the sum of a list, visit each element once and keep adding it to a running total.
Two programs
Fixed list and user-input list examples.
Live preview
Try custom input and verify the total instantly.
Interview-ready
Includes I/O, edge cases, complexity, and FAQ.
Prerequisites
Basic Python lists, loops, and integer input.
Live preview
Enter integers separated by commas or spaces.
Algorithm
Goal: compute a[0] + a[1] + ... + a[n-1].
1
Initialize
Set total = 0.
2
Traverse list
Add each value into total.
3
Print/return
After loop, total is final sum.
📜 Pseudocode
Pseudocode
function array_sum(arr):
total = 0
for value in arr:
total += value
return total1
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)}")📤 Output
Sum of the array elements: 15
2
Sum of an array (user input)
Reads n and then n numbers from user.
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)}")❓ FAQ
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.
🔄 Input / output examples
| Array | Sum |
|---|---|
| [1,2,3,4,5] | 15 |
| [10,-2,7] | 15 |
| [] | 0 |
Edge cases and pitfalls
n = 0
Empty list sum
Result remains 0.
Negative values
Valid input
They reduce total naturally.
Invalid input
Validate safely
Handle non-numeric values before summing.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Single pass | O(n) | O(1) |
Summary
- Use accumulator pattern: total starts at 0.
- Add each element once in one loop.
- Time O(n), extra space O(1).
Did you know?
The sum-of-array problem is a classic accumulator pattern: start with sum = 0, then add each element exactly once.
9 people found this page helpful
