Skip to main content

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
Submitted by devanshi.srivastava on June 21, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.