Central Tendency
Mode Frequency
Find the mode — the most frequently occurring value in a dataset. Tally
how many times each value appears, then pick the value with the highest
count. By hand, build a frequency dict and use max. With the library,
statistics.mode does both steps in one call.
By hand
Build counts by iterating the values and incrementing each key with
counts.get(v, 0) + 1. The trace shows the dict filling in: 3 is
incremented on iterations 0, 2, 4, 7 and ends at 4 — the highest count.
max(counts, key=counts.get) picks the key whose mapped count is largest.
values = [3, 7, 3, 5, 3, 7, 5, 3]
counts = {}
for v in values:
counts[v] = counts.get(v, 0) + 1
mode = max(counts, key=counts.get)
print('RESULT:', mode)
With the library
statistics.mode returns the single most frequent value. When multiple
values tie for the highest count, Python 3.8+ returns the first one
encountered; older Python raises StatisticsError. The data here has a
unique mode so neither edge case applies.
import statistics
from dalib.display import set_display
set_display()
values = [3, 7, 3, 5, 3, 7, 5, 3]
mode = statistics.mode(values)
print('statistics.mode:', mode)
print('RESULT:', mode)
statistics.mode: 3
RESULT: 3
Implementation notes
max(counts, key=counts.get)returns the key (value) whose count is largest; it matches Python 3.8+statistics.modefor a unique mode.- For multimodal data (multiple equally frequent values), use
statistics.multimode(Python 3.8+) to get all modes as a list. - Cross-reference:
frequency-count(python-data-basics) for the general pattern of tallying element frequencies.