Unit 3 Sets
Unit 3 Sets
Unit 3 Sets
Introduction
A set is created by using the set() function or placing all the elements within a pair of
curly braces.
Example
Days=set([“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”,”Sun”])
Months={“Jan”,”Feb”,”Mar”}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
Output
When the above code is executed, it produces the following result. Please note
how the order of the elements has changed in the result.
Intersection operation picks the elements that are common in both sets. “&” operator
or intersection() method is used to perform this operation.
Example
chemicalOne = {‘Na’, ‘K’, ‘Cl’}
chemicalTwo = {‘HCL’, ‘Cl’, ‘Ba’}
print(chemicalOne & chemicalTwo)
print(chemicalOne.intersection(chemicalTwo))
Output:
{‘Cl’}
{‘Cl’}
Difference
The difference in sets is similar to subtraction. When set B is subtracted from set A
i.e, Set A – Set B then we say that in the resulting set all the elements of Set B will be
removed from Set A. “-” (subtraction sign) or difference() method is used to perform
this operation.
Example
easyToLearn = {‘Python’, ‘JavaScript’, ‘C++’}
hardToLearn = {‘Assembly’, ‘C++’}
print(easyToLearn – hardToLearn)
print(easyToLearn.difference(hardToLearn))
print(‘Changing order we get: ‘)
print(hardToLearn – easyToLearn)
print(hardToLearn.difference(easyToLearn))
Output:
{‘JavaScript’ , ‘Python’}
{‘JavaScript’ , ‘Python’}
Changing order we get :
{‘Assembly’}
{‘Assembly’}
Symmetric Difference
The symmetric difference of two sets A and B is a set that contains elements in either
A or B but not both. “^” operator or symmetric_difference() method in python is used
to perform this operation.
Example
A = {1, 2, 3}
b = {3, 4, 5}
print(a ^ b)
print(a.symmetric_difference(b))
Output:
{1, 2, 4, 5}
{1, 2, 4, 5}
Methods in set
A Set in Python is a collection of unique elements which are unordered and
mutable.
We can add and remove elements form the set with the help of the below
functions
Add():Adds a given element to a set
clear():Removes all elements from the set
discard(): Removes the element from the set
pop():Returns and removes a random element from the set
remove(): Removes the element from the set
Example
s = {‘g’, ‘e’, ‘k’, ‘s’}
s.add(‘f’)
print(‘Set after updating:’, s)
s.discard(‘g’)
print(‘\nSet after updating:’, s)r updating:’, s)
print(‘\nPopped element’, s.pop())
print(‘Set after updating:’, s)
s.clear()
print(‘\nSet after updating:’, s)
Output