pythonsetsymmetric-difference

Please explain "set difference" in Python


Trying to learn Python I encountered the following:

>>> set('spam') - set('ham')
set(['p', 's'])

Why is it set(['p', 's']) - i mean: why is 'h' missing?


Solution

  • The - operator on Python sets is mapped to the difference method, which is defined as the members of set A which are not members of set B. So in this case, the members of "spam" which are not in "ham"are "s" and "p". Notice that this method is not commutative (that is, a - b == b - a is not always true).

    You may be looking for the symmetric_difference or ^ method:

    >>> set("spam") ^ set("ham")
    {'h', 'p', 's'} 
    

    This operator is commutative.