fluttersmith/py-snippetsGitHub ↗

Find the most frequent value

Return the most common item, breaking ties by first appearance.

Lists#countingO(n) time✓ 3 examples pass on 3.11–3.14

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]
  1. 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 iterable
Edit 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).

How it works

  • Counter.most_common(1) finds the top value in one pass.
  • Ties go to the value seen first, which is documented Counter behaviour.
  • An empty input raises ValueError, the same as max([]).

Complexity: O(n) time, O(k) space for k distinct values

Importfrom 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.