If you just want to remove the first n occurrences of something from the list, this is pretty easy to do with the generator:
def remove_n_dupes(remove_from, what, how_many): count = 0 for item in remove_from: if item == what and count < how_many: count += 1 else: yield item
Usage is as follows:
lst = [1,2,3,4,4,4,4,4] print list(remove_n_dupes(lst, 4, 3))
Saving a certain number of duplicates of any element is similarly easy if we use a small additional auxiliary storage:
from collections import Counter def keep_n_dupes(remove_from, how_many): counts = Counter() for item in remove_from: counts[item] += 1 if counts[item] <= how_many: yield item
Similar usage:
lst = [1,1,1,1,2,3,4,4,4,4,4] print list(keep_n_dupes(lst, 2))
Here you enter a list and the maximum number of items that you want to save. The caveat is that elements must be hashed ...
source share