Opposite of set.intersection in python?

You are looking for the symmetric difference; all elements that appear only in set a or in set b, but not both:

a.symmetric_difference(b)

From the set.symmetric_difference() method documentation:

Return a new set with elements in either the set or other but not both.

You can use the ^ operator too, if both a and b are sets:

a ^ b

while set.symmetric_difference() takes any iterable for the other argument.

The output is the equivalent of (a | b) - (a & b), the union of both sets minus the intersection of both sets.


The best way is a list comprehension.

a = [ 1,2,3,4]
b = [ 8,7,9,2,1]
c = [ element for element in a if element not in b] 
d = [ element for element in b if element not in a] 
print(c) 
# output is [ 3,4]
print(d) 
# output is  [8,7,9]

You can join both lists


a={1,2,4,5,6}
b={5,6,4,9}
c=(a^b)&b
print(c) # you got {9}

Tags:

Python

Set