Editor

Python Program to Find the Sum of Elements in a List

Beginner · Lists

This program adds up all the numbers in a list with a loop and a running total, the same way you would add a column of numbers by hand. It then uses the total to work out the average of the list.

Program

sum_of_list.py
numbers = [12, 45, 7, 23, 56, 89] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
total = 0 # the running total starts at zero
for num in numbers:
total += num # add each number to the total
print("List:", numbers)
print("Sum of elements:", total)
print("Average:", round(total / len(numbers), 2))
Output
List: [12, 45, 7, 23, 56, 89]
Sum of elements: 232
Average: 38.67

How it works

  1. total starts at 0, because adding a number to zero leaves it unchanged.
  2. The loop visits each number in the list and adds it to total; total += num is short for total = total + num.
  3. After the loop, total holds the sum of every element: 12 + 45 + 7 + 23 + 56 + 89 = 232.
  4. Dividing the sum by len(numbers), the count of elements, gives the average, and round(..., 2) keeps two decimal places.

Other ways to write it

Using sum()

Using sum()
numbers = [12, 45, 7, 23, 56, 89]
print("Sum of elements:", sum(numbers))
print("Sum with a starting value of 100:", sum(numbers, 100))
print("Sum of a tuple of decimals:", sum((1.5, 2.5, 3.0)))
Output
Sum of elements: 232
Sum with a starting value of 100: 332
Sum of a tuple of decimals: 7.0

The built-in sum() adds up a list or tuple of numbers in one call, and the optional second value is added to the total as a starting point.

Using a while loop

Using a while loop
numbers = [12, 45, 7, 23, 56, 89]
total = 0
i = 0
while i < len(numbers):
total += numbers[i] # numbers[i] is the element at index i
i += 1
print("Sum of elements:", total)
Output
Sum of elements: 232

A while loop walks the list by index, from 0 up to len(numbers) - 1, which is how many textbooks write it.

Try it yourself

Change the loop so it adds only the numbers greater than 20, and check that the sum becomes 213.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises