Remove all values within one list from another list?


Question

I am looking for a way to remove all values within a list from another list.

Something like this:

a = range(1,10)  
a.remove([2,3,7])  
print a  
a = [1,4,5,6,8,9]  
1
106
4/27/2017 6:52:25 PM

Python has a language feature called List Comprehensions that is perfectly suited to making this sort of thing extremely easy. The following statement does exactly what you want and stores the result in l3:

l3 = [x for x in l1 if x not in l2]

l3 will contain [1, 6].

382
8/23/2019 9:24:23 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon