How to Find the Mode in a Python List

Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

15 lines
Python 3.9+
from collections import Counter

def find_mode(numbers):
    if not numbers:
        return None
    counts = Counter(numbers)
    max_count = max(counts.values())
    modes = [num for num, count in counts.items() if count == max_count]
    return modes[0] if len(modes) == 1 else modes

if __name__ == "__main__":
    values = [3, 7, 3, 1, 7, 3, 9, 7, 3]
    result = find_mode(values)
    print(f"Values: {values}")
    print(f"Mode: {result}")

Output

stdout
Values: [3, 7, 3, 1, 7, 3, 9, 7, 3]
Mode: 3

How it works

The Counter(numbers) call builds a dictionary mapping each unique value to its frequency. max(counts.values()) finds the highest frequency, and a list comprehension collects all numbers that occur that many times. If only one mode exists we return that value; otherwise we return the list of modes. Returning None for an empty input avoids crashing on max() of an empty sequence.

Common mistakes

  • Forgetting to handle the empty list case, causing a ValueError from max().
  • Assuming there is always a single mode; ties are common and should return a list.
  • Using `numbers.count()` in a loop, which is O(n²) for large lists.

Variations

  1. Use `statistics.mode()` from the stdlib if you only need one mode and the list is non-empty.
  2. Use `statistics.multimode()` (Python 3.8+) to return all modes as a list.

Real-world use cases

  • Analyzing survey responses to find the most common answer value.
  • Processing log files to identify the most frequently occurring error code or IP address.
  • Computing the most frequent category in a dataset for data cleaning or feature engineering.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.