- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete elements with frequency atmost K in Python
While manipulating data from lists we may come across scenario where we have selectively remove elements form the list based on their frequency. In this article we will explore how to remove all elements from a list whose frequency is less than equal to 2. You can also change the value 2 to any number in the programs.
With count
The count methods keep the count of each element in the list. So we use it with a for loop and put a condition to only keep the elements whose count is greater than 2.
Example
listA = ['Mon', 3,'Tue','Mon', 9, 3, 3] # Printing original list print("Original List : " + str(listA)) # Remove elements with count less than 2 res = [i for i in listA if listA.count(i) > 2] # Result print("List after removing element with frequency < 3 : ",res)
Output
Running the above code gives us the following result −
Original List : ['Mon', 3, 'Tue', 'Mon', 9, 3, 3] List after removing element with frequency < 3 : [3, 3, 3]
With Counter
The Counter method counts the number of occurrences of an element in an iterable. So it is straight forward to use by passing the required list into it.
Example
from collections import Counter listA = ['Mon', 3,'Tue','Mon', 9, 3, 3] # printing original list print("Original List : " + str(listA)) # Remove elements with count less than 2 res = [ele for ele in listA if Counter(listA)[ele] > 2] # Result print("List after removing element with frequency < 3 : ",res)
Output
Running the above code gives us the following result −
Original List : ['Mon', 3, 'Tue', 'Mon', 9, 3, 3] List after removing element with frequency < 3 : [3, 3, 3]