Experiment No.
:- 06
Aim:
To write and execute Python programs to perform basic set operations:
a) Create an intersection of sets.
b) Create a union of sets.
c) Create set difference.
d) Check if two given sets have no elements in common.
T heory:
A set in Python is an unordered collection of unique elements. It allows various mathematical operations
such as:
● Intersection (& or [Link](set2)) – returns elements common to both sets.
● Union (| or [Link](set2)) – returns all unique elements from both sets.
● Difference (- or [Link](set2)) – returns elements present in one set but not the other.
● Disjoint (isdisjoint( )) – returns True if two sets have no elements in common.
a ) Program to create an intersection of sets
Program:
set1 = set(input("Enter elements of 1st set using space: ").split())
set2 = set(input("Enter elements of 2nd set using space: ").split())
ntersection_set = [Link](set2)
i
print("Set 1 =", set1)
print("Set 2 =", set2)
print("Intersection of sets =", intersection_set)
S ample Output:
Enter elements of 1st set using space: 1 2 3 4 5
Enter elements of 2nd set using space: 4 5 6 7
Set 1 = {'1', '2', '3', '4', '5'}
Set 2 = {'4', '5', '6', '7'}
Intersection of sets = {'4', '5'}
) Program to create a union of sets
b
Program:
set1 = set(input("Enter elements of 1st set using space: ").split())
set2 = set(input("Enter elements of 2nd set using space: ").split())
nion_set = [Link](set2)
u
print("Set 1 =", set1)
print("Set 2 =", set2)
print("Union of sets =", union_set)
S ample Output:
Enter elements of 1st set using space: a b c
Enter elements of 2nd set using space: b c d e
Set 1 = {'a', 'b', 'c'}
Set 2 = {'b', 'c', 'd', 'e'}
Union of sets = {'e', 'b', 'd', 'a', 'c'}
c ) Program to create set difference
Program:
set1 = set(input("Enter elements of 1st set using space: ").split())
set2 = set(input("Enter elements of 2nd set using space: ").split())
ifference_set = [Link](set2)
d
print("Set 1 =", set1)
print("Set 2 =", set2)
print("Difference of sets (set1 - set2) =", difference_set)
S ample Output:
Enter elements of 1st set using space: 10 20 30 40
Enter elements of 2nd set using space: 30 40 50
Set 1 = {'10', '20', '30', '40'}
Set 2 = {'30', '40', '50'}
Difference of sets (set1 - set2)= {'10', '20'}
) Program to check if two given sets have no elements in common
d
Program:
set1 = set(input("Enter elements of 1st set using space: ").split())
set2 = set(input("Enter elements of 2nd set using space: ").split())
if [Link](set2):
print("The sets have no elements in common.")
else:
print("The sets have common elements.")
S ample Output:
Enter elements of 1st set using space: 1 2 3
Enter elements of 2nd set using space: 4 5 6
The sets have no elements in common.
onclusion:
C
In this practical, we learned basic set operations like intersection, union, difference, and disjoint checks,
which help manage and compare unique data efficiently.