In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0]
and b = [0, 1, 1]
I\'d like to do something like
I attempted to find a more elegant solution, but the best I could do was basically the same thing that Dyno Fu said:
from copy import copy
def subtract_lists(a, b):
"""
>>> a = [0, 1, 2, 1, 0]
>>> b = [0, 1, 1]
>>> subtract_lists(a, b)
[2, 0]
>>> import random
>>> size = 10000
>>> a = [random.randrange(100) for _ in range(size)]
>>> b = [random.randrange(100) for _ in range(size)]
>>> c = subtract_lists(a, b)
>>> assert all((x in a) for x in c)
"""
a = copy(a)
for x in b:
if x in a:
a.remove(x)
return a