Using list comprehension to keep items not in second list
<p>I am trying to use list comprehension to remove a number of items from a list by just keeping those not specified.</p>

<p>For example if I have 2 lists <code>a = [1,3,5,7,10]</code> and <code>b = [2,4]</code> I want to keep all items from <code>a</code> that are not at an index corresponding to a number in <code>b</code>.</p>

<p>Now, I tried to use <code>y = [a[x] for x not in b]</code> but this produces a SyntaxError.</p>

<p><code>y = [a[x] for x in b]</code> works fine and keeps just exact the elements that i want removed.</p>

<p>So how do I achieve this? And on a side note, is this a good way to do it or should I use <code>del</code>?</p>

<p>You can use <a href="https://docs.python.org/2/library/functions.html#enumerate"><code>enumerate()</code></a> and look up indexes in <code>b</code>:</p>

<pre><code>&gt;&gt;&gt; a = [1, 3, 5, 7, 10]
&gt;&gt;&gt; b = [2, 4]
&gt;&gt;&gt; [item for index, item in enumerate(a) if index not in b]
[1, 3, 7]
</code></pre>

<p>Note that to improve the lookup time, better have the <code>b</code> as a <em>set</em> instead of a list. <a href="https://wiki.python.org/moin/TimeComplexity">Lookups into sets are <code>O(1)</code> on average</a> while in a list - <code>O(n)</code> where <code>n</code> is the length of the list.</p>

python list list-comprehension not-operator