Remove element from itertools.combinations while iterating?
<p>Given a list <code>l</code> and all combinations of the list elements is it possible to remove any combination containing <code>x</code> while iterating over all combinations, so that you never consider a combination containing <code>x</code> during the iteration after it is removed?</p>

<pre><code>for a, b in itertools.combinations(l, 2):
    if some_function(a,b):
        remove_any_tup_with_a_or_b(a, b)
</code></pre>

<p>My list <code>l</code> is pretty big so I don't want to keep the combinations in memory.</p>

<p>A cheap trick to accomplish this would be to filter by disjoint testing using a dynamically updated <code>set</code> of exclusion values, but it wouldn't actually avoid generating the combinations you wish to exclude, so it's not a major performance benefit (though <code>filter</code>ing using a C built-in function like <code>isdisjoint</code> will be faster than Python level <code>if</code> checks with <code>continue</code> statements typically, by pushing the <code>filter</code> work to the C layer):</p>

<pre><code>from future_builtins import filter  # Only on Py2, for generator based filter
import itertools

blacklist = set()
for a, b in filter(blacklist.isdisjoint, itertools.combinations(l, 2)):
    if some_function(a,b):
        blacklist.update((a, b))
</code></pre>

python iterator combinations