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)]
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
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With