pythonset-differencesymmetric-difference

Python sets: difference() vs symmetric_difference()


What is the difference between difference() and symmetric_difference() methods in python sets?


Solution

  • symmetric difference

    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}