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.
Python code
9 linesdef 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
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
- Use `statistics.mean(numbers)` from the standard library, though it raises `StatisticsError` on empty input.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.