Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove elements in one list present in another list [duplicate]

Tags:

python

list

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']

list2=["i","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!

like image 298
rodrigocf Avatar asked Jul 29 '13 21:07

rodrigocf


People also ask

How to remove all the elements from a list in Python?

One can iterate for all the elements of the removed list and remove those elements from the original list. set () can be used to perform this task and creating a new filtered list of all the elements that are not present in the remove element list.

How do I remove a list from a list in Excel?

Select a blank cell which is adjacent to the first cell of the list you want to remove, then enter formula =COUNTIF ($D$2:$D$6,A2) into the Formula Bar, and then press the Enter key.

How to maintain order of elements in a list?

If you want to maintain the ordering from initial list, then Donut's list comprehension based answer will do the trick. However, you can get better performance from the accepted answer by using set internally for checking whether element is present in other list. For example:

How to exclude values in one list from another in Excel?

Exclude values in one list from another with formula. Quickly exclude values in one list from another with Kutools for Excel. Easily exclude values in one list from another in Excel: The Select Same & Different Cells utility of Kutools for Excel can help you quickly selecting all same cells in one list based on values in another column.


2 Answers

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).

like image 183
alecxe Avatar answered Oct 14 '22 21:10

alecxe


What about leveraging set arithmetics?

diff = set(list1) - set(list2)
result = [o for o in list1 if o in diff]

Or even better (more efficient):

set2 = set(list2)
result = [o for o in list1 if o not in set2]
like image 36
Marsellus Wallace Avatar answered Oct 14 '22 20:10

Marsellus Wallace