While learning Python from http://www.learnpython.org/en/Sets I encountered the notion of symmetric_difference between sets. I thought it gave the same output as 'exclusive or' operations on sets. How is it different?
Asked
Active
Viewed 4,468 times
2 Answers
3
There is no difference. XORing sets works by calling the symmetric_difference
function. This is from the implementation of sets in sets.py:
def __xor__(self, other):
"""Return the symmetric difference of two sets as a new set.
(I.e. all elements that are in exactly one of the sets.)
"""
if not isinstance(other, BaseSet):
return NotImplemented
return self.symmetric_difference(other)
def symmetric_difference(self, other):
"""Return the symmetric difference of two sets as a new set.
(I.e. all elements that are in exactly one of the sets.)
"""
result = self.__class__()
data = result._data
value = True
selfdata = self._data
try:
otherdata = other._data
except AttributeError:
otherdata = Set(other)._data
for elt in ifilterfalse(otherdata.__contains__, selfdata):
data[elt] = value
for elt in ifilterfalse(selfdata.__contains__, otherdata):
data[elt] = value
return result
As you can see the XOR implementation makes sure that you are indeed working on sets only, but otherwise there are no differences.

Emil Vikström
- 90,431
- 16
- 141
- 175
1
Yes, it is pretty much the same, just XOR is an operation on booleans, and symmetric_difference
is an operation on sets. Actually, even your linked documentation page says this:
To find out which members attended only one of the events, use the "symmetric_difference" method
You can also see this more detailed mathematical explanation about relationship between logical XOR and symmetric difference on sets.
-
2Well, they're not _exactly_ the same thing, they're isomorphic operations (as discussed in the accepted answer at your link), but it makes perfect sense for Python to overload the `^` exclusive_OR operator to call the `symmetric_difference` method when it's applied to a pair of sets. – PM 2Ring Aug 31 '15 at 12:03
-
1I clarified this a bit. – mik01aj Aug 31 '15 at 12:04