Python: Find Most Frequent Element in a List or Array

Find the most frequent element in a Python list with Counter.most_common(), statistics.mode() and multimode(), pandas and NumPy, including ties.

Python

To find the most frequent element in a Python list, we count the elements with collections.Counter and call most_common(1); for all elements that share the top count, statistics.multimode() returns the full list. pandas and NumPy offer the same for large data, and NumPy’s fastest option only works with small non-negative integers.

MethodWhen to Use
collections.CounterAny hashable items, top N counts, the default choice
statistics.mode() / multimode()One most common value, or all values tied for first
pandas value_counts()Large sequences or columns of a DataFrame
NumPy bincount()Large arrays of small non-negative integers

In this tutorial, we explore each method, handle ties, unhashable items and empty input, and compare the methods. The examples run on Python 3.14 with NumPy 2.5 and pandas 3.0.

1. Find the Most Frequent Element using collections.Counter

A Counter is a dictionary that maps each element to the number of times it occurs. Its most_common(n) method returns the n most frequent elements with their counts, and indexing a missing element returns 0 instead of raising KeyError.

from collections import Counter

sequence = [1, 2, 3, 4, 1, 2, 1, 2, 1]
counter = Counter(sequence)
top_two = counter.most_common(2)        # [(1, 4), (2, 3)]
top, count = counter.most_common(1)[0]  # top = 1, count = 4
missing = counter[9]                    # 0

Counter uses each element as a dictionary key, so a list of lists raises TypeError: unhashable type: ‘list’. Converting the inner lists to tuples fixes it.

nested = [[1], [2], [1], [2], [1]]
counts = Counter(tuple(x) for x in nested)
most = counts.most_common(1)            # [((1,), 3)]

2. Ties: mode() and multimode()

When several elements share the highest count, most_common() lists them in the order they first appeared, and statistics.mode() returns the first of them. statistics.multimode() returns all tied elements.

import statistics

votes = ["tea", "coffee", "coffee", "tea", "juice"]
first_mode = statistics.mode(votes)          # 'tea'
all_modes = statistics.multimode(votes)      # ['tea', 'coffee']
counted = Counter(votes).most_common(2)      # [('tea', 2), ('coffee', 2)]

The pattern max(set(votes), key=votes.count) appears in many answers online. It counts the whole list once per distinct value, so it is slow for long lists, and its winner in a tie depends on the set order, which is not the list order.

3. Find the Most Frequent Element using pandas

A pandas Series counts values with value_counts(), sorted from the most to the least frequent, and mode() returns every value tied for first.

import pandas as pd

s = pd.Series(sequence)
top_value = s.value_counts().idxmax()        # 1
modes = s.mode().tolist()                    # [1]

4. Find the Most Frequent Element using NumPy

For arrays of small non-negative integers, np.bincount() counts each value by its position, and argmax() returns the most frequent one. For other values, np.unique(…, return_counts=True) works with any comparable type.

import numpy as np

arr = np.array(sequence)
by_bincount = np.bincount(arr).argmax()            # np.int64(1)
values, counts = np.unique(arr, return_counts=True)
by_unique = values[counts.argmax()]                # np.int64(1)

A negative number makes np.bincount() raise ValueError, and a very large one allocates a huge array, so np.unique() is the safer general choice.

5. Empty Input

Each method behaves differently on an empty list, so code that may receive one checks first.

empty_counter = Counter([]).most_common(1)     # []
empty_mode = statistics.mode([])               # StatisticsError: no mode for empty data
empty_multi = statistics.multimode([])         # []

6. Top Words in a Text

A word count is the classic use of Counter. Lowercasing and stripping punctuation first makes “Tea” and “tea,” count as the same word.

import re

text = "Tea, then more tea. Coffee? No, tea!"
words = re.findall(r"[a-z]+", text.lower())
top_words = Counter(words).most_common(2)      # [('tea', 3), ('then', 1)]

For removing the repeated values instead of counting them, see removing duplicates while keeping order.

7. Most Frequent Element FAQs

Rare values, filters and merging counts are the next things people try.

7.1. How do we get the least frequent element?

The last entry of counter.most_common() has the lowest count, and min(counter, key=counter.get) returns the same element. With ties, both return the first tied element they meet.

7.2. How do we count only elements that meet a condition?

We filter while counting, Counter(w for w in words if len(w) > 3). The generator keeps memory use low for large inputs.

7.3. Can Counter add counts from several lists?

Yes. counter.update(other_list) adds counts in place, and Counter(a) + Counter(b) returns a new combined counter.

8. Conclusion

The one-liner Counter(items).most_common(1) answers the question for any list of hashable values, and statistics.multimode() returns every value tied for first. pandas and NumPy count large data fast, with np.bincount() limited to small non-negative integers.

9. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.