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]
y = [a[x] for x not in b]
y = [a[x] for x in b]
You can use
enumerate() and look up indexes in
>>> 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 -
n is the length of the list.