PythonMastery
Python programs · Lists · beginner

Sum and average of a list in Python

Find the total and the average of a list of numbers with sum() and len(), and avoid the ZeroDivisionError you get from an empty list.

The average (mean) of a list is its total divided by the number of items. Python has sum() for the total and len() for the count.

The program

python
marks = [72, 85, 90, 64, 88]

total = sum(marks)
average = total / len(marks)

print("Marks:", marks)
print("Sum:", total)
print("Average:", average)
print(f"Average to 1 decimal place: {average:.1f}")
output
Marks: [72, 85, 90, 64, 88]
Sum: 399
Average: 79.8
Average to 1 decimal place: 79.8

How it works

An empty list

If the list is empty, len() is 0 and the division raises a ZeroDivisionError. A small function can check for that first:

python
def average(numbers):
    if not numbers:
        return None
    return sum(numbers) / len(numbers)

print(average([10, 20, 30, 40]))
print(average([]))
output
25.0
None

if not numbers: is true for an empty list. The standard library also has statistics.mean(), which raises a StatisticsError with a clear message for an empty list.

Learn the idea: Lists & Sequences, Functions & Scoping