ewhitt
ewhitt

Reputation: 947

Remove list entries that match any entry in another list

I have a list of curse words I want to match against other list to remove matches. I normally use list.remove('entry') on an individual basis, but looping through a list of entries against another list - then removing them has me stumped. Any ideas?

Upvotes: 1

Views: 3912

Answers (2)

Facundo Casco
Facundo Casco

Reputation: 10585

Using filter:

>>> words = ['there', 'was', 'a', 'ffff', 'time', 'ssss']
>>> curses = set(['ffff', 'ssss'])
>>> filter(lambda x: x not in curses, words)
['there', 'was', 'a', 'time']
>>> 

It could also be done with list comprehension:

>>> [x for x in words if x not in curses]

Upvotes: 10

Jay M
Jay M

Reputation: 4287

Use sets.

a=set(["cat","dog","budgie"])
b=set(["horse","budgie","donkey"])
a-b
->set(['dog', 'cat'])

Upvotes: 4

Related Questions