If I have a function
, how can I remove the first
items in a Python list that match that condition?
One solution is to iterate over each item, mark it for deletion (e.g., by setting it to
), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?
n = 3
return x < 5
data = [1, 10, 2, 9, 3, 8, 4, 7]
out = do_remove(data, n, condition)
print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains)