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!
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.
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.
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:
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.
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)
.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With