Python: Sets Operation List

We can perform following operations on Sets:

Set Union

It returns the union of two set.

set_1 = {1,2,3,4,5}
set_2 = {4,5,6,7,8}

set_3 = set_1.union(set_2)
print(set_3)

Output: {1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection

It is a set of elements that are common in both the sets.

set_1 = {1,2,3,4,5}
set_2 = {4,5,6,7,8}

set_3 = set_1.intersection(set_2)
print(set_3)

Output: {4, 5}

Set Difference

It  returns a set containing all the elements which are existing in the first set but not present in the second set. 

set_1 = {1,2,3,4,5}
set_2 = {4,5,6,7,8}

set_3 = set_1.difference(set_2)
print(set_3)

Output: {1, 2, 3}

Set Symmetric Difference

It is a set of elements in both the set, but not in both, i.e.excluding the intersection.

set_1={1,2,3,4,5}
set_2={4,5,6,7,8}

set_3 = set_1^set_2
print(set_3)

Output: {1, 2, 3, 6, 7, 8}

Tags