Compute a fast floating-point mean, optionally weighted.
What It Does and Why It Matters
fmean(data, weights=None) converts to float and often has better performance for real-valued measurements. If weights are given, their length must match the data.
statistics.fmean() has documented sample-size and input assumptions that must be checked before use.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
import statistics
print(statistics.fmean([10, 20, 30], weights=[1, 2, 1]))
How the Code Works
- The imports make these standard-library tools available: statistics.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
- The weighted mean is (10×1 + 20×2 + 30×1) divided by (1+2+1), which equals 20.0. The weights affect the result but do not need to add up to one.
Expected output:
20.0
For the demonstrated inputs, Python displays '20.0'. This result follows from the operation described above; change one input at a time to understand which rule matters.
Second Example: Compare Two Cases
Use a different input or a related operation to observe an important difference. The two examples help separate the general rule from one particular result.
import statistics
print(statistics.fmean([4, 6, 8]))
Expected output:
6.0
Where You Would Use This
Use this in calculations, data summaries, simulations or validation when the numerical assumptions match the task. Check input domains, units and precision before interpreting a result. A single example output does not prove a statistical conclusion.
Practice Exercise
Compute a weighted grade average.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Expecting fmean() to preserve Decimal or Fraction output types.
- Overlooking the documented condition: if weights are given, their length must match the data.
Key Takeaways
- Compute a fast floating-point mean, optionally weighted.
- fmean(data, weights=None) converts to float and often has better performance for real-valued measurements.
- Compute a weighted grade average.