Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting two lists in Python

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 c = a - b and have c be [2, 0] or [0, 2] order doesn't matter to me. This should throw an exception if a does not contain all elements in b.

Note this is different from sets! I'm not interested in finding the difference of the sets of elements in a and b, I'm interested in the difference between the actual collections of elements in a and b.

I can do this with a for loop, looking up the first element of b in a and then removing the element from b and from a, etc. But this doesn't appeal to me, it would be very inefficient (order of O(n^2) time) while it should be no problem to do this in O(n log n) time.

like image 660
wich Avatar asked Jan 15 '10 09:01

wich


People also ask

How do you subtract between two lists?

subtract two lists using Zip() Function In this method, we'll pass the two input lists to the Zip Function. Then, iterate over the zip object using for loop. On every iteration, the program will take an element from list1 and list2, subtract them and append the result into another list.

How do you subtract two lists in Numpy?

subtract() in Python. numpy. subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.


2 Answers

I know "for" is not what you want, but it's simple and clear:

for x in b:   a.remove(x) 

Or if members of b might not be in a then use:

for x in b:   if x in a:     a.remove(x) 
like image 77
Dyno Fu Avatar answered Oct 02 '22 08:10

Dyno Fu


I would do it in an easier way:

a_b = [e for e in a if not e in b ] 

..as wich wrote, this is wrong - it works only if the items are unique in the lists. And if they are, it's better to use

a_b = list(set(a) - set(b)) 
like image 26
pcv Avatar answered Oct 02 '22 10:10

pcv