How to Calculate the Average of a List of Numbers in Python

Compute the arithmetic mean of a numeric list using Python's built-in sum() and len() functions, returning 0.0 for an empty list.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

9 lines
Python 3.9+
def calculate_average(numbers):
    if not numbers:
        return 0.0
    return sum(numbers) / len(numbers)

if __name__ == "__main__":
    sample_numbers = [10, 20, 30, 40, 50]
    result = calculate_average(sample_numbers)
    print(f"Average: {result}")

Output

stdout
Average: 30.0

How it works

The function first checks if the input list is empty and returns 0.0 to avoid a ZeroDivisionError. For non-empty lists, it computes the sum of all elements using sum() and divides by the list length obtained from len(). Since division always produces a float in Python 3, the result is accurate even for integer inputs. The __name__ == "__main__" guard ensures the sample code only runs when the script is executed directly, not when it's imported as a module.

Common mistakes

  • Forgetting to handle an empty list, causing a ZeroDivisionError.
  • Using integer division (e.g., `//`) which truncates the decimal part for small numbers.
  • Assuming the list is numeric without validation, leading to TypeError when summing strings.

Variations

  1. Use `statistics.mean(numbers)` from the standard library, though it raises `StatisticsError` on empty input.
  2. Implement a manual loop accumulating total and count for cases where sum() is unavailable.

Real-world use cases

  • Calculating the average order value from a list of transaction amounts in a sales report.
  • Computing the mean response time from a list of API latency measurements for performance monitoring.
  • Obtaining the average test score from a list of student grades in a grading system.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.