I'm trying to compare two lists and get the new elements, including redundant elements. For instance, the result of :
l1 = [1,2,3,3,4]
l2 = [3,3,3,4,4,5,6]
Is :
l2 - l1 = [3,4,5,6]
You can easily understand that I can't do it with set because
set(l1) = (1,2,3,4)
set(l2) = (3,4,5,6)
The result would be : (5,6)
I don't want to do it with an iteration such as
[i for i in l1 if i not in l2 ]
Because it's too slow (see benchmark at Get difference between two lists)
Does anyone know how to do it without iteration and keep the redundant elements or iterative methods are the only way ?
Thanks !
Benchmarking of the solutions :
I benchmarked both of the given solutions and here's the result :
import random
init1 = list(range(10000))
init2 = [i*random.randint(1,50) for i in range(10000)]
# Put both solution in function, diff1 = remove method, diff2 = Counter method
import time
tic1 = time.clock()
print(diff1(init2,init1))
toc1 = time.clock()
tic2 = time.clock()
print(diff2(init2,init1))
toc2 = time.clock()
print(toc1-tic1)
print(toc2-tic2)
And the results are :
2.756271607145601 for diff1
0.028116911506909315 for diff2