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 itera
Using list comprehensions:
n = 3
data = [1, 10, 2, 9, 3, 8, 4, 7]
count = 0
def counter(x):
global count
count += 1
return x
def condition(x):
return x < 5
filtered = [counter(x) for x in data if count < n and condition(x)]
This will also stop checking the condition after n elements are found thanks to boolean short-circuiting.