Python Practice › List Programs › Program 3

Sum of all elements

EasyList Programs · 3 of 100

Write a Python program to calculate the sum of all elements in a list.

Advertisement
Input
[12, 7, 33, 5, 21]
Output
78 78

Approach

  1. Add each item to a total, or use sum().

Solution

Python
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.

More list programs

← All 100 List Programs

1 thought on “Sum of all elements”

Leave a Comment