Chapter 8 Set
Chapter 8 Set
Empty set:-
s=set()
s={} it is not set. it is dict
It is hetrogeneous:-
{1,5.4,"abc"}
It is iterable:-
for k in {1,2,3}:
print(k)
It is mutable:-
s1.add(4)
s1.remove(4)
Membership operator:-
10 in s1
10 not in s1
Set comparisons:-
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which
we can check whether a set is subset, superset, or equivalent to other set. The boolean true or false is
returned depending upon the items present inside the sets.
{1,2,3}=={3,1,2} #True
Matrix Computers (Page 3 of 5)
10/564 Kaveri Path, Mansarovar Jaipur-302020 Rajasthan
9414752750, 9414930104, 9414244351, 0141-2399633
{1,2,3,4}>{1,2,3} #True
{1,2,3,4}>={1,2,3} #True
{1,2,3}>{1,2,3} #False
{1,2,3}>={1,2,3} #True
Identity operator:-
s1=set()
s2=set()
s1 is s2 #False
s1=set([1,2,3])
s2=set([1,2,3])
s1 is s2 #False
Reference copy
s1={1,2,3}
s2=s1
s1 is s2 #True
True/Shallow Copy
s2=s1.copy()
s1 is s2 #False
7 difference(set) will return extra elements of calling set which are not in
argument set. It will not update calling set
s1.difference(s2) #will return extra elements of s1 which are not in s2.
#It will not update s1
8 difference_update(set) will return extra elements of calling set which are not in
argument set. It will update calling set
s1.difference_update(s2) It will update s1
9 intersection() It returns a new set that contains only the common elements of
both the sets.
10 intersection_update(set)It removes the items from the original set that are not present in
both the sets
s1.intersection(s2) #return common elements but not update s1
s1.intersection_update(s2) #return common elements and update s1
11 symmetric_difference(set)
12 symmetric_difference_update(set)
Update a set with the symmetric difference of itself and another.
s1.symmetric_difference(s2) #return non common elements but will not update s1
s1.symmetric_difference_update(s2) #return non common elements but will update s1
FrozenSets:-
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set can
not be changed and therefore it can be used as a key in dictionary. The elements of the frozen set can not
be changed after the creation. We cannot change or append the content of the frozen sets by using the
methods like add() or remove(). The frozenset() method is used to create the frozenset object. The iterable
sequence is passed into this method which is converted into the frozen set as a return type of the method.