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.
Python code
15 linesfrom 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
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
- Use `statistics.mode()` from the stdlib if you only need one mode and the list is non-empty.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.