Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Multimode of List
In Python, finding the multimode of a list means identifying all elements that occur with the highest frequency. Unlike mode (single most frequent element), multimode returns all elements tied for the highest count.
Using statistics.multimode()
Python's statistics module provides a built-in multimode() function that returns all most frequent elements ?
import statistics
numbers = [9, 8, 8, 7, 7, 7, 6, 6, 6, 6]
result = statistics.multimode(numbers)
print("Multimode:", result)
print("Most frequent element appears:", numbers.count(result[0]), "times")
The output of the above code is ?
Multimode: [6] Most frequent element appears: 4 times
Using Dictionary Counting
We can manually count frequencies using a dictionary and find all elements with maximum count ?
def find_multimode(data):
# Count frequency of each element
frequency = {}
for item in data:
frequency[item] = frequency.get(item, 0) + 1
# Find maximum frequency
max_count = max(frequency.values())
# Return all elements with maximum frequency
multimode_values = [item for item, count in frequency.items() if count == max_count]
return multimode_values
# Example with multiple modes
numbers = [1, 2, 2, 3, 3, 4]
result = find_multimode(numbers)
print("Multimode:", result)
print("Each appears:", numbers.count(result[0]), "times")
The output of the above code is ?
Multimode: [2, 3] Each appears: 2 times
Using Counter from collections
The Counter class provides an elegant solution for frequency counting ?
from collections import Counter
def multimode_counter(data):
count = Counter(data)
max_freq = max(count.values())
return [item for item, freq in count.items() if freq == max_freq]
# Test with string characters
text = "programming"
chars = list(text)
result = multimode_counter(chars)
print("Characters:", chars)
print("Multimode:", result)
The output of the above code is ?
Characters: ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g'] Multimode: ['r', 'g', 'm']
Comparison
| Method | Time Complexity | Advantages | Best For |
|---|---|---|---|
statistics.multimode() |
O(n) | Built-in, concise | Quick solutions |
| Dictionary counting | O(n) | No imports, customizable | Learning purposes |
Counter |
O(n) | Readable, feature-rich | Complex frequency analysis |
Conclusion
Use statistics.multimode() for simple multimode calculation. For custom logic or additional frequency analysis, use Counter from collections. All methods have O(n) time complexity where n is the list size.
