Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of set.intersection in python?

Tags:

python

set

In Python you can use a.intersection(b) to find the items common to both sets.

Is there a way to do the disjoint opposite version of this? Items that are not common to both a and b; the unique items in a unioned with the unique items in b?

like image 242
user4847061 Avatar asked Apr 29 '15 15:04

user4847061


People also ask

What is the opposite of intersection in Python?

Intersection: Elements two sets have in common. Union: All the elements from both sets. Difference: Elements present on one set, but not on the other. Symmetric Difference: Elements from both sets, that are not present on the other.

What is the opposite of intersection in set theory?

In mathematics, the symmetric difference, also known as the disjunctive union, of two sets is the set of elements which are in either of the sets and not in their intersection.

What is the opposite of a set union?

In terms of set theory, union is the set of all the elements that are in either set, or in both, whereas intersection is the set of all distinct elements that belong to both the sets.

What is set intersection in Python?

Python Set intersection() Method The intersection() method returns a set that contains the similarity between two or more sets. Meaning: The returned set contains only items that exist in both sets, or in all sets if the comparison is done with more than two sets.


2 Answers

You are looking for the symmetric difference; all elements that appear only in set a or in set b, but not both:

a.symmetric_difference(b) 

From the set.symmetric_difference() method documentation:

Return a new set with elements in either the set or other but not both.

You can use the ^ operator too, if both a and b are sets:

a ^ b 

while set.symmetric_difference() takes any iterable for the other argument.

The output is the equivalent of (a | b) - (a & b), the union of both sets minus the intersection of both sets.

like image 187
Martijn Pieters Avatar answered Oct 08 '22 09:10

Martijn Pieters


a={1,2,4,5,6} b={5,6,4,9} c=(a^b)&b print(c) # you got {9} 
like image 44
Kaung Yar Zar Avatar answered Oct 08 '22 08:10

Kaung Yar Zar