Set difference versus set subtraction

David542 picture David542 · Jun 22, 2015 · Viewed 51.6k times · Source

What distinguishes - and .difference() on sets? Obviously the syntax is not the same, one is a binary operator, 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])

Answer

Padraic Cunningham picture Padraic Cunningham · Jun 22, 2015

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