Reference · Statistics

stats.mean

signature
stats.mean(list) -> float

What it does

The arithmetic mean of a list of numbers, as a float: the sum divided by the count. It is Python's statistics.mean: the sum is compensated and rounded once, so the answer is the correctly rounded mean, not the running sum divided by the count. Ints and floats can mix; the answer is always a float.

Examples

print(stats.mean([1, 2, 3, 4]), stats.mean([1, 2, 3]), stats.mean([1.5, 2.5]))print(stats.mean([0.1, 0.2, 0.3]), (0.1 + 0.2 + 0.3) / 3)
output
2.5 2.0 2.00.2 0.20000000000000004

Edge cases

print(stats.mean([5]), stats.mean([-1, 1]))print(stats.mean([9007199254740993, 9007199254740993]))print(stats.mean([1e308, 1e308]))print(stats.mean([dec("1.5"), dec("2.5")] | map(float)))
output
5.0 0.09007199254740992.01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002.0

Errors

The mean of no data is a runtime error, not an error value: an empty list or null stops the request. So does a list with something that is not a number in it, or a decimal. Guard with len when the list can be empty.

this one fails
print(stats.mean([]))
output
line 1: `stats.mean` requires at least one data point
this one fails
print(stats.mean([1, "2"]))
output
line 1: `stats.mean` expects a list of numbers, but item 1 is str
let xs = []print(len(xs) > 0 && stats.mean(xs))
output
false

Chaining

In a pipeline the list comes first, so stats.mean takes it as its only argument:

print([3, 1, 2] | stats.mean)print([{ total: 12.5 }, { total: 30 }, { total: 7.5 }] | vec.column("total") | stats.mean)print([1, 2, 3, 10] | filter((x) => x < 10) | stats.mean)
output
2.016.6666666666666682.0

See also

stats.fmean, stats.median, stats.geometric_mean, stats.harmonic_mean, stats.describe, sum, math.fsum

Thread
8Useful? Like it, or add to its thread below.

Thread 0 posts

On stats.mean(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo