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])
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