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
Count Frequency of Highest Frequent Elements in Python
Finding the frequency of the most common element in a list is a common programming task. Python provides several approaches, from basic nested loops to efficient built-in methods using collections.Counter.
So, if the input is like [1,5,8,5,6,3,2,45,7,5,8,7,1,4,6,8,9,10], then the output will be 3 as the number 5 occurs three times and is the most frequent element.
Using Nested Loops (Basic Approach)
This approach compares each element with all other elements to count occurrences ?
def count_max_frequency(nums):
max_count = 0
length = len(nums)
for i in range(length):
count = 1
for j in range(i + 1, length):
if nums[i] == nums[j]:
count += 1
if max_count < count:
max_count = count
return max_count
nums = [1, 5, 8, 5, 6, 3, 2, 45, 7, 5, 8, 7, 1, 4, 6, 8, 9, 10]
result = count_max_frequency(nums)
print(f"Maximum frequency: {result}")
Maximum frequency: 3
Using collections.Counter (Efficient Approach)
Counter is the most efficient way to count element frequencies in Python ?
from collections import Counter
def count_max_frequency_counter(nums):
counter = Counter(nums)
return counter.most_common(1)[0][1]
nums = [1, 5, 8, 5, 6, 3, 2, 45, 7, 5, 8, 7, 1, 4, 6, 8, 9, 10]
result = count_max_frequency_counter(nums)
print(f"Maximum frequency: {result}")
# Show the complete frequency count
counter = Counter(nums)
print(f"All frequencies: {dict(counter)}")
print(f"Most common element: {counter.most_common(1)[0]}")
Maximum frequency: 3
All frequencies: {1: 2, 5: 3, 8: 3, 6: 2, 3: 1, 2: 1, 45: 1, 7: 2, 4: 1, 9: 1, 10: 1}
Most common element: (5, 3)
Using Dictionary for Manual Counting
This approach manually builds a frequency dictionary ?
def count_max_frequency_dict(nums):
frequency = {}
# Count frequencies
for num in nums:
frequency[num] = frequency.get(num, 0) + 1
# Find maximum frequency
return max(frequency.values())
nums = [1, 5, 8, 5, 6, 3, 2, 45, 7, 5, 8, 7, 1, 4, 6, 8, 9, 10]
result = count_max_frequency_dict(nums)
print(f"Maximum frequency: {result}")
Maximum frequency: 3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops | O(n²) | O(1) | Small lists, no extra imports |
| Counter | O(n) | O(n) | Most efficient, feature-rich |
| Dictionary | O(n) | O(n) | Understanding the logic |
Conclusion
Use collections.Counter for the most efficient solution with O(n) time complexity. The nested loop approach works for small datasets but becomes inefficient for larger lists due to O(n²) complexity.
