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
List: [12, 45, 7, 23, 56, 89] Sum of elements: 232 Average: 38.67
How it works
totalstarts at 0, because adding a number to zero leaves it unchanged.- The loop visits each number in the list and adds it to
total;total += numis short fortotal = total + num. - After the loop,
totalholds the sum of every element: 12 + 45 + 7 + 23 + 56 + 89 = 232. - Dividing the sum by
len(numbers), the count of elements, gives the average, andround(..., 2)keeps two decimal places.
Other ways to write it
Using sum()
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
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.
Related programs
- Find the Average of Numbers
- Find the Cumulative Sum of a List
- Multiply All Numbers in a List
- Find the Sum of a List Using Recursion
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises