Python | Delete elements with frequency atmost K

There are many methods that can be employed to perform the deletion in the list. Be it remove function, pop function and many other functions. But most of the times, we usually don’t deal with the simple deletion, but with certain constraints. This article discusses certain ways in which we can delete only those elements which occurs less than K times.

Method #1 : Using list comprehension + count()
The idea applied here is to construct a new list using list comprehension and insert only those elements which occur more than K times. The count operation is done with the help of count function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# remove elements less than and equal K 
# using list comprehension + count()
  
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K
K = 2
  
# using list comprehension + count()
# remove elements less than K 
res = [ i for i in test_list if test_list.count(i) > K]
  
# print result
print("The list removing elements less than and equal K  : " + str(res))

chevron_right


Output :

The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K  : [3, 2, 3, 3, 2, 2, 2]

 

Method #2 : Using Counter() + list comprehension
This problem can be efficiently solved using the Counter function that precomputes the count of each elements in list so that the decision to keep or reject a particular element takes lesser time.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# remove elements less than and equal K 
# using Counter() + list comprehension
from collections import Counter
  
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K
K = 2
  
# using Counter() + list comprehension
# remove elements less than K 
freq = Counter(test_list)
res = [ele for ele in test_list if freq[ele] > K]
  
# print result
print("The list removing elements less than and equal K  : " + str(res))

chevron_right


Output :

The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K  : [3, 2, 3, 3, 2, 2, 2]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.