In Python you can use a.intersection(b)
to find the items common to both sets.
Is there a way to do the disjoint opposite version of this? Items that are not common to both a
and b
; the unique items in a
unioned with the unique items in b
?
Intersection: Elements two sets have in common. Union: All the elements from both sets. Difference: Elements present on one set, but not on the other. Symmetric Difference: Elements from both sets, that are not present on the other.
In mathematics, the symmetric difference, also known as the disjunctive union, of two sets is the set of elements which are in either of the sets and not in their intersection.
In terms of set theory, union is the set of all the elements that are in either set, or in both, whereas intersection is the set of all distinct elements that belong to both the sets.
Python Set intersection() Method The intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.
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.
a={1,2,4,5,6} b={5,6,4,9} c=(a^b)&b print(c) # you got {9}
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