Preserve tied categories with Python statistics.multimode
A report of the most common deployment region can hide a tie if it prints only one category. Return all equally frequent leaders, then make the reporting policy explicit.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save this as demo_python_multimode_preserve_category_ties.py. Use that filename to avoid shadowing a standard-library module.
from statistics import mode, multimode
regions = ["west", "east", "west", "east", "north"]
print("single mode:", mode(regions))
print("all leaders:", multimode(regions))
print("reversed leaders:", multimode(reversed(regions)))
print("sorted report:", sorted(multimode(regions)))
print("empty leaders:", multimode([]))
leaders = multimode(regions)
print("unique winner:", leaders[0] if len(leaders) == 1 else "none")Run it:
python3 demo_python_multimode_preserve_category_ties.pyOutput:
single mode: west
all leaders: ['west', 'east']
reversed leaders: ['east', 'west']
sorted report: ['east', 'west']
empty leaders: []
unique winner: nonemode chooses the first encountered leader when frequencies tie. multimode keeps all leaders in encounter order. Sorting the returned strings gives this report a stable presentation order; it does not break the tie or change the counts.
Input policy and limits
Define how missing or malformed categories are handled before counting. This example uses hashable strings with exact spelling, so differently capitalized names remain separate categories. An empty leader list means no observations, while multiple leaders mean a tie. Neither case supplies a unique winner.
Clean up
In the same Bash session, remove the source file and the empty working directory:
rm -- demo_python_multimode_preserve_category_ties.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before deleting anything else.
References
Acknowledgements
This post was created with assistance from AI.