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)]
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)]
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)}
You can do such operations by converting the lists to sets. Set difference:
r = set(B)-set(A)
Convert to list if necessary: list(r)
Working on sets is efficient compared to running "in" operations on lists: using lists vs sets for list differences