# Python Program to Illustrate Different Set Operations

ⓘ Sponsored by 10xer.co

In Python, a set is an unordered collection of unique and immutable objects. This means that a set can contain multiple elements, but each element in the set is unique, and the order in which the elements are stored is not guaranteed. Sets are commonly used to eliminate duplicate items from a list, perform mathematical set operations such as union, intersection, and difference, and to test if an element is present in a collection.

## Python Code : #

The below Python program illustrates different set operations:

``````
# Define two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union of sets
print("Union of sets:", set1.union(set2))

# Intersection of sets
print("Intersection of sets:", set1.intersection(set2))

# Difference of sets
print("Difference of sets:", set1.difference(set2))

# Symmetric difference of sets
print("Symmetric difference of sets:", set1.symmetric_difference(set2))

# Subset of sets
print("Subset of sets:", set1.issubset(set2))

# Superset of sets
print("Superset of sets:", set1.issuperset(set2))

``````

Explanation:

1. The program defines two sets called set1 and set2.

2. The union() method is used to find the union of the two sets. The resulting set contains all elements that are in either set.

3. The intersection() method is used to find the intersection of the two sets. The resulting set contains all elements that are common to both sets.

4. The difference() method is used to find the difference of the two sets. The resulting set contains all elements that are in set1 but not in set2.

5. The symmetric_difference() method is used to find the symmetric difference of the two sets. The resulting set contains all elements that are in either set, but not in both sets.

6. The issubset() method is used to check whether set1 is a subset of set2.

7. The issuperset() method is used to check whether set1 is a superset of set2.

For Example:

``````
Union of sets: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection of sets: {4, 5}
Difference of sets: {1, 2, 3}
Symmetric difference of sets: {1, 2, 3, 6, 7, 8}
Subset of sets: False
Superset of sets: False

``````

ⓘ Sponsored by 10xer.co