Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract two lists of tuples from each other

I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^).

A = [(0, 1)]
B = [(0, 0), (0,1), (0, 2)]

Essentially what I want is:

B - A = [(0, 0), (0, 2)]
like image 928
Ghazal Avatar asked Dec 28 '25 07:12

Ghazal


2 Answers

You can use list comprehension to solve this problem:

[item for item in B if item not in A]

More discussion can be found here

like image 106
nbryans Avatar answered Dec 30 '25 21:12

nbryans


If there are no duplicate tuples in B and A, might be better to keep them as sets, and use the difference of sets:

A = [(0, 1)]
B = [(0, 0), (0,1), (0, 2)]
diff = set(B) - set(A) # or set(B).difference(A)
print(diff)
# {(0, 0), (0, 2)}

You could perform other operations like find the intersection between both sets:

>>> set(B) & set(A)
{(0, 1)}

Or even take their symmetric_difference:

>>> set(B) ^ set(A)
{(0, 0), (0, 2)}
like image 34
Moses Koledoye Avatar answered Dec 30 '25 23:12

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!