Python Program - Illustrate Different Set Operations

htt‮/:sp‬/www.theitroad.com

here's a Python program that illustrates different set operations:

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

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

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

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

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

In this program, we first create two sets: set1 containing the integers 1 through 5, and set2 containing the integers 4 through 8.

We can perform different set operations on these sets using the following methods:

  • union() method returns the union of two sets, i.e., all the elements that are in either set. We use the union() method to print the union of set1 and set2.

  • intersection() method returns the intersection of two sets, i.e., all the elements that are common to both sets. We use the intersection() method to print the intersection of set1 and set2.

  • difference() method returns the difference between two sets, i.e., all the elements that are in the first set but not in the second set. We use the difference() method to print the difference between set1 and set2, as well as the difference between set2 and set1.

  • symmetric_difference() method returns the symmetric difference between two sets, i.e., all the elements that are in either set but not in both sets. We use the symmetric_difference() method to print the symmetric difference between set1 and set2.

We can use these set operations to manipulate and analyze sets of data in Python.