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>The accepted answer was a little too magical for my liking.  Here's one where the flow is hopefully a bit clearer to follow:</p>

<pre><code>def matchCondition(x):
    return x &lt; 5


def my_gen(L, drop_condition, max_drops=3):
    count = 0
    iterator = iter(L)
    for element in iterator:
        if drop_condition(element):
            count += 1
            if count &gt;= max_drops:
                break
        else:
            yield element
    yield from iterator


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

print(list(my_gen(example, drop_condition=matchCondition)))
</code></pre>

<p>It's similar to logic in <a href="http://stackoverflow.com/a/39580319/674039">davidism</a> answer, but instead of checking the drop count is exceeded on every step, we just short-circuit the rest of the loop.</p>

<p><em>Note:</em> If you don't have <a href="https://docs.python.org/3/whatsnew/3.3.html"><code>yield from</code></a> available, just replace it with another for loop over the remaining items in <code>iterator</code>.  </p>

python list list-comprehension