Thomas Johnson Thomas Johnson - 2 months ago 8
Python Question

Pythonic way to remove the first N items in a list that match a condition

If I have a function

matchCondition(x)
, how can I remove the first
N
items in a Python list that match that condition?

One solution is to iterate over each item and mark it for deletion (e.g., by setting it to
None
), keeping track of the number of marked items, and then filter the list with a list comprehension. Is there a simpler or more Pythonic way to do this?

Just to clarify what I'm trying to accomplish:

N = 3
def matchCondition(x):
return x < 5

l = [1, 10, 2, 9, 3, 8, 4, 7]

# l = do_remove(l, N, matchCondition)

# l is now [10, 9, 8, 4, 7] (1, 2, and 3 have been removed)

Answer

One way using itertools:

from itertools import count, filterfalse

data = [1, 10, 2, 9, 3, 8, 4, 7]
output = filterfalse(lambda L, c=count(): L < 5 and next(c) < 3, data)

Then list(output), gives you:

[10, 9, 8, 4, 7]