remove all instances of a set of different values from another list?

Viewed 37
list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
list2 = ['a', 3, 'b']

Is it possible to have the values in list2 completely removed from list1 and output:

[1, c, 5]
3 Answers

You can try casting them from lists to sets!

>>> list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
>>> list2 = ['a', 3, 'b']

>>> set(list1) - set(list2)
# returns => {1, 5, 'c'}

>>> list(set(list1) - set(list2))
# returns => [1, 5, 'c']

Sets are a native python object, similar to lists, but they are unordered and every item is unique. With sets, you can perform set operations like "subset", "union", and "difference" (which is what this is).


Note: This technique only works if you don't care about duplicates or item order. If you must retain either or both of those things, a list comprehension or other filtering technique would be better.

With the given lists,

>>> list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
>>> list2 = ['a', 3, 'b']

Use list comprehension

>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 5]

When we change list2, the output is as expected:

>>> list2 = ['a', 5, 'b']
>>> list3 = [item for item in list1 if item not in list2]
>>> list3
[1, 'c', 3, 3, 3]

After looking at the other answers, you might want to try this hybrid approach that combines the best of both:

>>> list1 = [1, 'a', 'c', 3, 5, 3, 3, 'a', 'b']
>>> list2 = ['a', 3, 'b']
>>> remove = frozenset(list2)
>>> list3 = [x for x in list1 if x not in remove]
>>> list3
[1, 'c', 5]
>>> 
Related