What is Python symmetric_difference and how is it different from XOR operation?

4.5k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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.

2
On

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.