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

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.

naive.py
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)
library.py
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.mode for 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.