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])
A way of modifying a set by removing the elements belonging to another set. Subtraction of sets is indicated by either of the symbols – or \. For example, A minus B can be written either A – B or A \ B.
Set difference is a generalization of the idea of the complement of a set and as such is sometimes called the relative complement of T with respect to S. The symmetric difference between two sets S and T is the union of S – T and T – S.
Python Set difference() MethodThe difference() method returns a set that contains the difference between two sets. Meaning: The returned set contains items that exist only in the first set, and not in both sets.
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
On a quick glance it may not be quite evident from the documentation but buried deep inside a paragraph is dedicated to differentiate the method call with the operator version
Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like
set('abc') & 'cbs'
in favor of the more readableset('abc').intersection('cbs')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With