Thursday, August 13, 2009

Python: Remove items from a list that occur in another list

Suppose that you have two list x and y. How to remove items from list x that occur in list y?

Method 1

>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> y = [4, 7, 9]
>>> list(set(x) - set(y))
[1, 2, 3, 5, 6, 8]

Method 2

>>> x = [1, 2, 3, 4, 5, 6, 7, 8]
>>> y = [4, 7, 9]
>>> [i for i in x if i not in y]
[1, 2, 3, 5, 6, 8]
I have presented two methods for removing items from list x that occur in list y. If you have better method, please leave a comment.