Remove the first N items that match a condition in a Python list
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p>

<p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), 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?</p>

<pre><code>n = 3

def condition(x):
    return x &lt; 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)
</code></pre>

<p>Using list comprehensions:</p>

<pre><code>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 &lt; 5

filtered = [counter(x) for x in data if count &lt; n and condition(x)]
</code></pre>

<p>This will also stop checking the condition after <em>n</em> elements are found thanks to boolean short-circuiting.</p>

python list list-comprehension