Python Program - Illustrate Different Set Operations
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 theunion()method to print the union ofset1andset2.intersection()method returns the intersection of two sets, i.e., all the elements that are common to both sets. We use theintersection()method to print the intersection ofset1andset2.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 thedifference()method to print the difference betweenset1andset2, as well as the difference betweenset2andset1.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 thesymmetric_difference()method to print the symmetric difference betweenset1andset2.
We can use these set operations to manipulate and analyze sets of data in Python.
