Explain Codes LogoExplain Codes Logo

Calculating arithmetic mean (one type of average) in Python

python
functions
best-practices
dataframe
Anton ShumikhinbyAnton Shumikhin·Jan 30, 2025
TLDR

Snippet to find the mean using Python's statistics.mean():

from statistics import mean average = mean([1, 2, 3, 4, 5]) # Who would thought math could be so mean!

If you're too hardcore to use imports, divide the sum by the number of elements:

average = sum([1, 2, 3, 4, 5]) / 5 # DIY till you DIE!

Both snippets calculate the mean of the list [1, 2, 3, 4, 5].

Ninja tricks for arithmetic mean

Let's go into the arithmetic mean stealth mode - an understanding of the concept is super beneficial:

No number, no problem

Ever met the empty list_exception? Here's how to dodge it:

numbers = [] average = sum(numbers) / len(numbers) if numbers else None # Rest assured, empty lists won't break your code!

NumPy: for when the data doesn't fit in your pocket anymore

import numpy as np average = np.mean(np.array([1, 2, 3, 4, 5])) # When standard Python mean is too mean for large datasets!

With NumPy, even an empty array won't cause an existential crisis, it just returns NaN.

When Python version gives you cognitive dissonance

For Python oldies (versions 3.1-3.3), stats is a shoulder to lean on. For the youngsters, it's all about statistics.

Manual means more control

When going DIY, remember to convert integer to float, lest you unexpectedly stumble upon integer division:

average = sum([1.0, 2, 3, 4, 5]) / len([1, 2, 3, 4, 5]) # Float like a butterfly!

Think about the edge cases

Considering edge cases is like wearing a seatbelt while driving. It's safe and prudent:

When the list sneakily adopts other types

Remember, diversity in lists is great, but not for the mean calculation:

numbers = [1, 'two', 3] average = mean([float(i) for i in numbers if isinstance(i, (int, float))]) # Remember: Strings can't math!

Infinity and NaN are just number outsiders

Understand how infinity or NaN values might crash your mean-calculation party:

numbers = [1, 2, 3, float('inf')] average = np.mean(numbers) # Result will be 'inf' # Infinity: it's like a number, but bigger! numbers = [1, 2, 3, float('nan')] average = np.mean(numbers) # Result will be 'nan' # NaN: the introvert of numbers!

SciPy for the Stat nerds

SciPy is like NumPy, just with extra awesome statistical capabilities:

from scipy import stats average = stats.mean([1, 2, 3, 4, 5]) # Scipy: Bigger, better, meaner!