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>Write a generator that takes the iterable, a condition, and an amount to drop.  Iterate over the data and yield items that don't meet the condition.  If the condition is met, increment a counter and don't yield the value.  Always yield items once the counter reaches the amount you want to drop.</p>

<pre><code>def iter_drop_n(data, condition, drop):
    dropped = 0

    for item in data:
        if dropped &gt;= drop:
            yield item
            continue

        if condition(item):
            dropped += 1
            continue

        yield item

data = [1, 10, 2, 9, 3, 8, 4, 7]
out = list(iter_drop_n(data, lambda x: x &lt; 5, 3))
</code></pre>

<p>This does not require an extra copy of the list, only iterates over the list once, and only calls the condition once for each item.  Unless you actually want to see the whole list, leave off the <code>list</code> call on the result and iterate over the returned generator directly.</p>

python list list-comprehension