Write a Python Program to Illustrate Different Set Operations

Sets are a fundamental data structure in Python that can be used to store a collection of unique items.

In this tutorial, we will discuss different set operations and provide examples of how to use them in Python.


Set operations allow us to perform various operations on sets such as union, intersection, difference, and symmetric difference.

Let’s dive into each of these operations and see how they work.

Union

The union of two sets is a new set that contains all the elements that are in either set.

The union operation can be performed using the “|” operator or the union() method.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1 | set2
print(set3) # Output: {1, 2, 3, 4}

set4 = set1.union(set2)
print(set4) # Output: {1, 2, 3, 4}

Intersection

The intersection of two sets is a new set that contains only the elements that are in both sets.

The intersection operation can be performed using the “&” operator or the intersection() method.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1 & set2
print(set3) # Output: {2, 3}

set4 = set1.intersection(set2)
print(set4) # Output: {2, 3}

Difference

The difference of two sets is a new set that contains only the elements that are in the first set but not in the second set.

The difference operation can be performed using the “-” operator or the difference() method.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1 - set2
print(set3) # Output: {1}

set4 = set1.difference(set2)
print(set4) # Output: {1}

Symmetric difference

The symmetric difference of two sets is a new set that contains only the elements that are in either of the sets but not in both.

The symmetric difference operation can be performed using the “^” operator or the symmetric_difference() method.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1 ^ set2
print(set3) # Output: {1, 4}

set4 = set1.symmetric_difference(set2)
print(set4) # Output: {1, 4}

Conclusion

In this tutorial, we have discussed the different set operations available in Python.

These operations can be used to manipulate sets and obtain new sets based on certain criteria.

We have provided examples of how to perform each of these operations using both the operators and the corresponding methods.