3

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)]
Ghazal
  • 101
  • 2
  • 13

3 Answers3

3

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

Community
  • 1
  • 1
nbryans
  • 1,507
  • 17
  • 24
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)}
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • When using methods like `.difference` you don't explicitly need to convert `A` to a set as it'll take any iterable. – Jon Clements Sep 18 '16 at 16:09
0

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

Community
  • 1
  • 1
picmate 涅
  • 3,951
  • 5
  • 43
  • 52