Python Program to Illustrate Different Set Operations

By | October 3, 2021
Python Program to Illustrate Different Set Operations

A set is a mutable collection of unordered and unique elements. Python set has many inbuilt methods that can be used to perform various set operations, such as union and intersection. Here in this article, we have provided python source code to illustrate different set operations.

Please note that in order to keep the code simple and comprehensible for newcomers, we will be considering only 2 sets here. Nonetheless, in practical scenarios, you might need to work on many more sets.

Prerequisite Topics to Create The Python Program

Steps to Create the Python Program

  1. Ask the user to enter elements in the first and second sets.
  2. Use the various in-built python methods to perform the set operations.

Python Program to Illustrate Different Set Operations

Code:

print("Enter 7 distinct elements in set a: ")
a= set(input() for i in range(7))

print("Enter 7 distinct elements in set b: ")
b= set(input() for i in range(7))

print("A union B is: ", a|b)
print("A intersection b is: ", a&b)
print("Set difference between a and b is: ", a-b)
print("Symmetric Difference between a and b is: ", a^b)

Output 1:

Enter 7 distinct elements in set a: 
1
2
3
4
5
6
7
Enter 7 distinct elements in set b: 
5
6
7
8
9
10
11
A union B is: {'9', '5', '6', '2', '8', '11', '1', '4', '10', '7', '3'}
A intersection b is: {'5', '7', '6'}
Set difference between a and b is: {'2', '4', '1', '3'}
Symmetric Difference between a and b is: {'11', '10', '3', '9', '2', '8', '1', '4'}

Output 2:

Vamware
Enter 7 distinct elements in set a: 
12
16
20
21
27
33
56
Enter 7 distinct elements in set b: 
33
56
14
40
19
18
11
A union B is: {'33', '11', '40', '12', '27', '19', '14', '21', '20', '18', '56', '16'}
A intersection b is: {'56', '33'}
Set difference between a and b is: {'12', '27', '21', '20', '16'}
Symmetric Difference between a and b is: {'11', '40', '12', '19', '18', '21', '27', '16', '14', '20'}

Conclusion

Performing set operations is common in programming and if you’re aiming for data science then you must have good knowledge of the same. To better understand the concept of set operations you can experiment with performing them on 3 sets, then 4 sets, and so on.

People are also reading:

Vamware
Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

Leave a Reply

Your email address will not be published.