Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set difference versus set subtraction

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]) 
like image 696
David542 Avatar asked Jun 22 '15 18:06

David542


People also ask

What is set subtraction?

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.

What do you mean by set difference?

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.

Can we subtract two sets in Python?

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.


2 Answers

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

like image 93
Padraic Cunningham Avatar answered Sep 19 '22 16:09

Padraic Cunningham


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 readable set('abc').intersection('cbs').

like image 45
Abhijit Avatar answered Sep 19 '22 16:09

Abhijit