pysnippets.lists.most_frequent
Find the most frequent value
most_frequent(items: Iterable[H]) -> H
Return the most common item, breaking ties by first appearance.
The popular one-liner max(set(items), key=items.count) is O(n²), and on a tie its answer depends on set order.
most_frequent.py✓ ruff · mypy --strict
from collections import Counter
from collections.abc import Hashable, Iterable
from typing import TypeVar
H = TypeVar("H", bound=Hashable)
def most_frequent(items: Iterable[H]) -> H:
"""Return the most common value in ``items``; on a tie, the one seen first."""
top = Counter(items).most_common(1)
if not top:
raise ValueError("most_frequent() arg is an empty iterable")
return top[0][0]- most_common(1) is a single O(n) pass
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2])2passed on Python 3.11 to 3.14: >>> most_frequent("abracadabra")'a'passed on Python 3.11 to 3.14: >>> most_frequent([])Traceback (most recent call last):...ValueError: most_frequent() arg is an empty iterableEdit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
Counter.most_common(1)finds the top value in one pass.- Ties go to the value seen first, which is documented
Counterbehaviour. - An empty input raises
ValueError, the same asmax([]).
Complexity: O(n) time, O(k) space for k distinct values
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.lists.most_frequent import most_frequentNo dependencies: copy most_frequent.py into your project, or clone the repo.Adapted from most-frequent in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Rewritten with Counter: O(n), deterministic ties, clear empty error. Suggest an edit.