Delete items from a list in another list


This question already has an answer here:

  • Remove all the elements that occur in one list from another 5 answers

I have list1 and list2. list2 is a group of words that have to be removed from list1, for example:

list1=['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me', 'me']


Desired output:

list3=['paste', 'text', 'text', 'here', 'here', 'here', 'my']

I have tried different versions using 'for' but no results so far.

Any ideas would be appreciated!

Use list comprehension:

>>> list1 = ['paste', 'text', 'text', 'here', 'here', 'here', 'my', 'i', 'i', 'me', 'me']
>>> list2 = ["i","me"]
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
['paste', 'text', 'text', 'here', 'here', 'here', 'my']

NOTE: Lookups in lists are O(n), consider making a set from list2 instead - lookups in sets are O(1).