- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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]
- Related Articles
- Delete List Elements in Python
- Delete Tuple Elements in Python
- Delete Dictionary Elements in Python
- Python – Remove Elements in K distance with N
- Python – Extract elements with equal frequency as value
- Delete elements in range in Python
- Python program to print Rows where all its Elements’ frequency is greater than K
- List frequency of elements in Python
- Python – Restrict Elements Frequency in List
- Python – Elements with factors count less than K
- Maximum score after flipping a Binary Matrix atmost K times in C++
- Delete leaf nodes with value k in C++?
- Python - Sort rows by Frequency of K
- Python – K middle elements
- Python – Fractional Frequency of elements in List

Advertisements