voiDnyx voiDnyx - 9 months ago 39
Python Question

Using list comprehension to keep items not in second list

I am trying to use list comprehension to remove a number of items from a list by just keeping those not specified.

For example if I have 2 lists

a = [1,3,5,7,10]
b = [2,4]
I want to keep all items from
that are not at an index corresponding to a number in

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

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

So how do I achieve this? And on a side note, is this a good way to do it or should I use


You can use enumerate() and look up indexes in b:

>>> a = [1, 3, 5, 7, 10]
>>> b = [2, 4]
>>> [item for index, item in enumerate(a) if index not in b]
[1, 3, 7]

Note that to improve the lookup time, better have the b as a set instead of a list. Lookups into sets are O(1) on average while in a list - O(n) where n is the length of the list.