bpo-35892: Fix mode() and add multimode() (#12089)
diff --git a/Doc/library/statistics.rst b/Doc/library/statistics.rst
index 81119da..97e1c3a 100644
--- a/Doc/library/statistics.rst
+++ b/Doc/library/statistics.rst
@@ -37,7 +37,7 @@
These functions calculate an average or typical value from a population
or sample.
-======================= =============================================
+======================= ===============================================================
:func:`mean` Arithmetic mean ("average") of data.
:func:`fmean` Fast, floating point arithmetic mean.
:func:`harmonic_mean` Harmonic mean of data.
@@ -45,8 +45,9 @@
:func:`median_low` Low median of data.
:func:`median_high` High median of data.
:func:`median_grouped` Median, or 50th percentile, of grouped data.
-:func:`mode` Mode (most common value) of discrete data.
-======================= =============================================
+:func:`mode` Single mode (most common value) of discrete or nominal data.
+:func:`multimode` List of modes (most common values) of discrete or nomimal data.
+======================= ===============================================================
Measures of spread
------------------
@@ -287,12 +288,12 @@
.. function:: mode(data)
- Return the most common data point from discrete or nominal *data*. The mode
- (when it exists) is the most typical value, and is a robust measure of
- central location.
+ Return the single most common data point from discrete or nominal *data*.
+ The mode (when it exists) is the most typical value and serves as a
+ measure of central location.
- If *data* is empty, or if there is not exactly one most common value,
- :exc:`StatisticsError` is raised.
+ If there are multiple modes, returns the first one encountered in the *data*.
+ If *data* is empty, :exc:`StatisticsError` is raised.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
@@ -310,6 +311,27 @@
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
+ .. versionchanged:: 3.8
+ Now handles multimodal datasets by returning the first mode encountered.
+ Formerly, it raised :exc:`StatisticsError` when more than one mode was
+ found.
+
+
+.. function:: multimode(data)
+
+ Return a list of the most frequently occurring values in the order they
+ were first encountered in the *data*. Will return more than one result if
+ there are multiple modes or an empty list if the *data* is empty:
+
+ .. doctest::
+
+ >>> multimode('aabbbbccddddeeffffgg')
+ ['b', 'd', 'f']
+ >>> multimode('')
+ []
+
+ .. versionadded:: 3.8
+
.. function:: pstdev(data, mu=None)