Batu Lab NotesPractical developer guides

Report the mode only when it is unique

By Batu · English technical notes

Also published in our Blogger archive.

A single mode is useful only when one category is more frequent than every other category. Python’s statistics.mode() returns one value, but since Python 3.8 it resolves a tie by returning the first tied value encountered. That behavior is deterministic, yet it does not establish that the result is unique.

This example first calls statistics.multimode() for a small set of tool votes. It returns every value with the maximum frequency in first-encounter order. Because both lint and format occur twice, the assertion records the tie and the program prints none instead of assigning a misleading winner. If exactly one leader existed, the conditional would use mode() to obtain and report that sole category.

This approach applies to discrete, hashable values such as labels, status names, or integer codes. It is not a way to infer preference strength, and a tie may call for a separate decision rule rather than silence. Empty input also needs deliberate handling: multimode() returns an empty list, whereas mode() raises StatisticsError. NaN values can cause surprising counting behavior in these statistics, so they should not stand in for missing categories. multimode() was added in Python 3.8; see the official mode and multimode documentation.

AI assistance disclosure: this article was drafted with AI assistance and its example was synthetically tested.

from statistics import mode, multimode

votes = ["lint", "format", "lint", "format", "test"]
leaders = multimode(votes)

assert leaders == ["lint", "format"]

if len(leaders) == 1:
    print(f"unique mode: {mode(votes)}")
else:
    print("unique mode: none")
unique mode: none