Python Practice › List Programs › Program 3
Sum of all elements
Write a Python program to calculate the sum of all elements in a list.
Input
[12, 7, 33, 5, 21]
Output
78 78
Approach
- Add each item to a total, or use
sum().
Solution
numbers = [12, 7, 33, 5, 21]total = 0for n in numbers: total += nprint(total, sum(numbers))Output
78 78
Line by line
Lines 3-4
The loop adds each number to the running total.
Line 5
The built-in sum() gives the same answer.
Learn the concept
New to this topic? Read the lesson, then come back.
1 thought on “Sum of all elements”