What is Python Symmetric Difference and how does it differ from an XOR operation?

When learning Python from http://www.learnpython.org/en/Sets, I came across the concept of symmetric_difference between sets. I thought he gave the same result as "exclusive" or "set operations". How is that different?

+4
source share
2 answers

There is no difference. XORing works by calling a function symmetric_difference. 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 ensures that you really only work with sets, but otherwise there are no differences.

+3

, , XOR - , symmetric_difference - . :

, , "_"

XOR .

+1

All Articles