Python Sets - Program to Demonstrate Use of Python Sets
Program 1 -
set1={1,2,3,4} #creation
print(set1)
print(type(set1))
set1.add(10) #addition
print(set1)
set1.remove(10)
print(set1) #remove
set1.discard(3)
print(set1) #discard
set1.pop()
print(set1) #pop
set1.clear()
print(set1) #clear
Output -
{1, 2, 3, 4}
<class 'set'>
{1, 2, 3, 4, 10}
{1, 2, 3, 4}
{1, 2, 4}
{2, 4}
set()
Methods Used In Program 1 -
add() method - To add the desired element in the end of the set.
remove() method - To remove the desired element from the set.
discard() method - Used to discard or delete the element from the set.
pop() method - Used to pop an element from the set.
clear() method - To delete the whole set.
Program 2 -
set1={1,2,3,4}
set2={4,6,7,8}
print(set1)
print(set2)
#union
print("Union of set1 and set2: ", set1.union(set2))
print("Union of set1 and set2: ", set1 | set2)
#intersection
print("Intersection of set1 and set2: ", set1.intersection(set2))
print("Intersection of set1 and set2: ", set1 & set2)
#difference
print("Difference of set1 and set2: ", set1.difference(set2))
print("Difference of set1 and set2: ", set1 - set2)
#symmetric difference
print("Symmetric difference of set1 and set2: ", set1.symmetric_difference(set2))
print("Symmetric difference of set1 and set2: ", set1 ^ set2)
print(4 in set1)
print(set1.isdisjoint(set2))
print(set1.issubset(set2))
set3=frozenset([10,20,30,40,50])
print(set3)
Output -
{1, 2, 3, 4}
{8, 4, 6, 7}
Union of set1 and set2: {1, 2, 3, 4, 6, 7, 8}
Union of set1 and set2: {1, 2, 3, 4, 6, 7, 8}
Intersection of set1 and set2: {4}
Intersection of set1 and set2: {4}
Difference of set1 and set2: {1, 2, 3}
Difference of set1 and set2: {1, 2, 3}
Symmetric difference of set1 and set2: {1, 2, 3, 6, 7, 8}
Symmetric difference of set1 and set2: {1, 2, 3, 6, 7, 8}
True
False
False
frozenset({40, 10, 50, 20, 30})
Methods Used In Program 2 -
union() method - Return a set that contains all the elements from the original set, and all the items from the specified set.
intersection() method - Return the similarity between two sets. For example. set1 = {1,2,3,4}, set2 = {8,6,4,7}, result will be {4} because set1 and set2 both had the integer 4.
difference method() - Return a set that contains difference between two sets.
symmetric difference() method - Returns the symmetric difference of two sets.
disjoint() function - Checks whether the two sets are disjoint or not, it it is disjoint then returns true, else return false.
issubset() function - Return true if all the items in the set exists in the specified set, else returns false.
frozenset() - It is an immutable version of Python set object.
0 Comments