Python | Remove elements of list that are repeated less than k times
Given a list of integers (elements may be repeated), write a Python program to remove the elements that are repeated less than k times.
Examples:
Input : lst = ['a', 'a', 'a', 'b', 'b', 'c'], k = 2 Output : ['a', 'a', 'a', 'b', 'b'] Input : lst = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4], k = 3 Output : [1, 1, 1, 1, 3, 3, 3]
Approach #1 : Pythonic naive
Counter() from collections module construct a dictionary mapping values to counts and save them in ‘counted’. Then we make use of ‘temp_lst’ to store the elements that need to be removed. Finally, we traverse through the given list and append all elements that are not in ‘temp_lst’ to ‘res_lst’ containing the required output.
# Python3 program to Remove elements of # list that repeated less than k times from collections import Counter def removeElements(lst, k): counted = Counter(lst) temp_lst = [] for el in counted: if counted[el] < k: temp_lst.append(el) res_lst = [] for el in lst: if el not in temp_lst: res_lst.append(el) return(res_lst) # Driver code lst = ['a', 'a', 'a', 'b', 'b', 'c'] k = 2print(removeElements(lst, k)) |
['a', 'a', 'a', 'b', 'b']
Approach #2 : Efficient Approach
The efficient approach to use Counter method is to construct a dictionary mapping value to counts and then use a list comprehension to filter for counts larger than a specified value. This approach is both time and space efficient.
# Python3 program to Remove elements of # list that repeated less than k times from collections import Counter def removeElements(lst, k): counted = Counter(lst) return [el for el in lst if counted[el] >= k] # Driver code lst = ['a', 'a', 'a', 'b', 'b', 'c'] k = 2print(removeElements(lst, k)) |
['a', 'a', 'a', 'b', 'b']
Recommended Posts:
- Python | Remove repeated sublists from given list
- Python | Remove last K elements of list
- Remove multiple elements from a list in Python
- Python | Remove trailing empty elements from given list
- Python | Remove unordered duplicate elements from a list
- Python | Remove all values from a list present in other list
- Python | Repeat each element K times in list
- Python | Add similar value multiple times in list
- Python | Check if any element occurs n times in given list
- Python | Check if k occurs atleast n times in a list
- Python list remove()
- Python | Remove Duplicates from a List
- Python | Remove given element from the list
- Python | Remove None values from list
- Python | Remove all digits from a list of strings
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.



