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
Delete elements with frequency atmost K in Python
While manipulating data from lists we may come across scenarios where we need to selectively remove elements from the list based on their frequency. In this article we will explore how to remove all elements from a list whose frequency is at most K (less than or equal to K). We'll demonstrate with K=2, but you can change this value to any number in the programs.
Using count() Method
The count() method returns the frequency of each element in the list. We use it with list comprehension and put a condition to only keep elements whose count is greater than K ?
Example
data = ['Mon', 3, 'Tue', 'Mon', 9, 3, 3]
# Printing original list
print("Original List:", data)
# Remove elements with frequency <= 2 (keep only frequency > 2)
K = 2
result = [item for item in data if data.count(item) > K]
# Result
print(f"List after removing elements with frequency <= {K}:", result)
Original List: ['Mon', 3, 'Tue', 'Mon', 9, 3, 3] List after removing elements with frequency <= 2: [3, 3, 3]
Using Counter from collections
The Counter class from the collections module efficiently counts the occurrences of elements in an iterable. This approach is more efficient for large lists since it counts frequencies only once ?
Example
from collections import Counter
data = ['Mon', 3, 'Tue', 'Mon', 9, 3, 3]
# Printing original list
print("Original List:", data)
# Count frequencies once
freq_count = Counter(data)
K = 2
# Remove elements with frequency <= K
result = [item for item in data if freq_count[item] > K]
# Result
print(f"List after removing elements with frequency <= {K}:", result)
Original List: ['Mon', 3, 'Tue', 'Mon', 9, 3, 3] List after removing elements with frequency <= 2: [3, 3, 3]
Performance Comparison
| Method | Time Complexity | Best For |
|---|---|---|
count() |
O(n²) | Small lists |
Counter |
O(n) | Large lists, better performance |
Conclusion
Use Counter for better performance as it counts frequencies only once. The count() method is simpler but less efficient for large datasets since it recounts for each element.
