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

 Live Demo

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

 Live Demo

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]

Updated on: 04-May-2020

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements