What is the difference between difference() and symmetric_difference() methods in python sets?
If there are a set_A and set_B, then the symmetric difference between them will be equal to the union of set_A and set_B without the intersection between the two. There is also another method to get the symmetric difference between two sets, by the use of an operator “^“. # using ^ operator.
Difference: Elements present on one set, but not on the other. Symmetric Difference: Elements from both sets, that are not present on the other.
The symmetric difference between two sets is also called as disjunctive union. Symmetric difference between two sets is a set of elements that are in both sets but not in their intersection.
In Terms of Other Set Operations Other set operations can be used to define the symmetric difference. From the above definition, it is clear that we may express the symmetric difference of A and B as the difference of the union of A and B and the intersection of A and B. In symbols we write: A ∆ B = (A ∪ B) – (A ∩ B).
If A
and B
are sets
A - B
is everything in A
that's not in B
.
>>> A = {1,2,3} >>> B = {1,4,5} >>> >>> A - B {2, 3} >>> B - A {4, 5}
A.symmetric_difference(B)
are all the elements that are in exactly one set, i.e. the union of A - B
and B - A
.
>>> A.symmetric_difference(B) {2, 3, 4, 5} >>> (A - B).union(B - A) {2, 3, 4, 5}
The difference between two sets (or groups of things) is not exactly the same as arithmetic difference.
Consider the two sets above (blue and green) as being two sets, or circles, that intersect each other. The yellow part being the intersection, what belongs to both sets.
Now consider what the set resulting from subtracting the greens from the blues should have. Should it have any greens? No. It will have blues that are not greens (or are not yellows, in the same logic). This is also true the other way around.
So you can get items from one set or the other, but not from both. I want to introduce to you, my little friend, symmetric difference. The gives you blues and greens, but not the yellows.
>>> a = {1,2,3} >>> b = {1,4,5} >>> a - b ## asymmetric difference {2, 3} >>> b - a ## asymmetric difference {4, 5} >>> a ^ b ## symmetric difference {2, 3, 4, 5}
The asymmetric difference depends on what you do with a
and b
, or in what order you compare them. Look at it one way you get one thing, look a different way you get a different thing. Where the asymmetric difference, by definition, does not care which way you look at it.
Note. This is analogous behavior to that of a XOR. Hence the operator chosen in the python language. ^
is also used as a binary XOR if you give it numbers.
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