Last modified: Feb 05, 2026 By Alexander Williams
Python Average Function Guide: Calculate Mean
Finding an average is a common task. Python makes it easy. This guide shows you how.
We will cover built-in tools and custom functions. You will learn to handle different data types.
What is an Average?
An average, or mean, is a central value. It sums numbers and divides by the count. It gives a data snapshot.
Python has several ways to find it. The best method depends on your data and needs.
Using the Statistics Module
Python's statistics module is built for this. Import it to use the mean() function.
This function is reliable. It works with lists, tuples, and other iterables.
# Import the statistics module
import statistics
# A list of numbers
data = [10, 20, 30, 40, 50]
# Calculate the average
average_value = statistics.mean(data)
# Print the result
print(f"The average is: {average_value}")
The average is: 30
The statistics.mean() function does the math for you. It is the standard way.
Calculating Average with sum() and len()
You can calculate it manually. Use sum() to add numbers. Use len() to count them.
This method is simple. It does not need any imports.
# A list of numbers
numbers = [5, 15, 25, 35, 45]
# Manual average calculation
total = sum(numbers)
count = len(numbers)
average = total / count
print(f"Sum: {total}, Count: {count}, Average: {average}")
Sum: 125, Count: 5, Average: 25.0
This is a fundamental approach. It helps you understand the core logic behind the mean.
Creating a Custom Average Function
You can write your own function. This is useful for learning and customization. For more on structuring functions, see our Python Function Syntax Guide for Beginners.
A custom function lets you add error checks. You can handle empty lists.
def calculate_average(num_list):
"""
Calculates the average of a list of numbers.
Returns None if the list is empty.
"""
if not num_list: # Check if the list is empty
return None
return sum(num_list) / len(num_list)
# Test the function
scores = [88, 92, 79, 95]
result = calculate_average(scores)
print(f"Test 1 - Average score: {result}")
empty_list = []
result2 = calculate_average(empty_list)
print(f"Test 2 - Empty list result: {result2}")
Test 1 - Average score: 88.5
Test 2 - Empty list result: None
This function is reusable. It shows how to manage a function's return value. Learn more about this in our guide on Python Function Return Values Explained.
Handling Different Data Types
Data does not always come in a simple list. You might have a tuple or dictionary.
Average of a Tuple
Tuples are immutable sequences. The statistics.mean() function works with them too.
import statistics
temperature_data = (22.5, 24.0, 19.5, 21.0, 23.5)
avg_temp = statistics.mean(temperature_data)
print(f"Average temperature: {avg_temp}")
Average temperature: 22.1
Average from a Dictionary
Dictionaries store key-value pairs. You often need the average of the values.
monthly_sales = {'Jan': 4000, 'Feb': 5200, 'Mar': 4800}
# Get all values from the dictionary
sales_values = monthly_sales.values()
# Calculate the average
average_sales = sum(sales_values) / len(monthly_sales)
print(f"Average monthly sales: ${average_sales:.2f}")
Average monthly sales: $4666.67
Common Errors and How to Avoid Them
You might encounter errors. Knowing them helps you write better code.
Empty Sequence Error
Dividing by zero causes an error. Always check if your list has items first.
def safe_average(data):
if len(data) == 0:
return 0 # Or handle it another way
return sum(data) / len(data)
TypeError with Non-Numeric Data
The sum() function needs numbers. Strings will cause a TypeError.
# This will cause an error
# mixed_data = [10, '20', 30]
# total = sum(mixed_data) # TypeError!
Ensure your data is clean. Convert strings to numbers if needed.
Advanced Example: Weighted Average
A weighted average considers importance. Each number has a corresponding weight.
You multiply each number by its weight. Then sum and divide by the sum of weights.
grades = [85, 90, 78]
weights = [0.3, 0.5, 0.2] # Must sum to 1.0
# Calculate weighted sum
weighted_sum = sum(g * w for g, w in zip(grades, weights))
# The sum of weights is 1.0, so average is just the weighted sum
weighted_average = weighted_sum
print(f"Weighted average grade: {weighted_average}")
Weighted average grade: 85.3
This technique is powerful for grades, finances, and surveys.
Conclusion
Calculating averages in Python is straightforward. You have many options.
Use statistics.mean() for a quick, standard solution. Use sum() and len() for manual control.
Write custom functions for specific logic. Always handle empty lists and wrong data types.
This skill is essential for data analysis. Practice with different data structures. For more on making your functions versatile, explore Python Function Argument Unpacking: A Comprehensive Guide