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 Python Program to Illustrate Different Set Operations
**

- Python sets and methods.
- Python input-output .

##
**
Steps to Create the Python Program
**

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

##
**
Python Program to Illustrate Different Set Operations
**

###
**
Python 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:
**

```
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:
**

- Python Program to Transpose a Matrix
- WAP to print three numbers in descending order
- Python Program to Find the Size of Image
- Most Asked Pattern Programs in C
- Python Program to Find LCM
- Python Program to Convert Kilometers to Miles
- How many Centimeters in a Foot through Python?
- C Program to Convert Feet into Inches
- WAP in C++ & Python to Reverse a String

## Leave a Comment on this Post