0
0
PythonProgramBeginner · 2 min read

Python Program to Find Sum of All Elements in List

You can find the sum of all elements in a list in Python by using the built-in sum() function like total = sum(your_list).
📋

Examples

Input[1, 2, 3]
Output6
Input[10, -5, 7, 3]
Output15
Input[]
Output0
🧠

How to Think About It

To find the sum of all elements in a list, think of adding each number one by one until you have added every element. You start with zero and keep adding each element to this total until the list ends.
📐

Algorithm

1
Start with a total sum set to zero.
2
Go through each element in the list one by one.
3
Add the current element's value to the total sum.
4
After all elements are added, return or print the total sum.
💻

Code

python
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
Output
15
🔍

Dry Run

Let's trace the list [1, 2, 3, 4, 5] through the code using sum().

1

Initialize list

numbers = [1, 2, 3, 4, 5]

2

Call sum()

sum(numbers) adds 1 + 2 + 3 + 4 + 5

3

Calculate total

total = 15

4

Print result

print(total) outputs 15

IterationCurrent ElementRunning Total
111
223
336
4410
5515
💡

Why This Works

Step 1: Using sum() function

The sum() function automatically adds all elements in the list without needing a loop.

Step 2: Starting total at zero

The function starts adding from zero, so if the list is empty, the result is zero.

Step 3: Adding each element

Each element is added one by one to the total until all elements are processed.

🔄

Alternative Approaches

Using a for loop
python
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
    total += num
print(total)
This method shows the addition process step-by-step but is longer than using sum().
Using reduce() from functools
python
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)
This uses a functional programming style but is less readable for beginners.

Complexity: O(n) time, O(1) space

Time Complexity

The program must visit each element once to add it, so the time grows linearly with the list size.

Space Complexity

Only a single variable is used to store the sum, so extra space does not grow with input size.

Which Approach is Fastest?

Using sum() is fastest and most readable; loops are clear but longer; reduce() is less common and slightly slower.

ApproachTimeSpaceBest For
sum() functionO(n)O(1)Simple and fast summing
for loopO(n)O(1)Learning how addition works step-by-step
reduce() functionO(n)O(1)Functional programming style
💡
Use the built-in sum() function for the simplest and fastest way to add list elements.
⚠️
Beginners often try to add elements without initializing the total sum or forget to loop through all elements.