pythonsetsubtractionset-difference

Set difference versus set subtraction


What distinguishes - and .difference() on sets? Obviously the syntax is not the same. One is a binary operator, and the other is an instance method. What else?

s1 = set([1,2,3])
s2 = set([3,4,5])

>>> s1 - s2
set([1, 2])
>>> s1.difference(s2)
set([1, 2])

Solution

  • set.difference, set.union... can take any iterable as the second arg while both need to be sets to use -, there is no difference in the output.

    Operation         Equivalent   Result
    s.difference(t)   s - t        new set with elements in s but not in t
    

    With .difference you can do things like:

    s1 = set([1,2,3])
    
    print(s1.difference(*[[3],[4],[5]]))
    
    {1, 2}
    

    It is also more efficient when creating sets using the *(iterable,iterable) syntax as you don't create intermediary sets, you can see some comparisons here