Calculating arithmetic mean (one type of average) in Python
Snippet to find the mean using Python's statistics.mean():
If you're too hardcore to use imports, divide the sum by the number of elements:
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:
NumPy: for when the data doesn't fit in your pocket anymore
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:
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:
Infinity and NaN are just number outsiders
Understand how infinity or NaN values might crash your mean-calculation party:
SciPy for the Stat nerds
SciPy is like NumPy, just with extra awesome statistical capabilities:
Was this article helpful?