Social Media

1/08/2019

Methods related to Set

add(): This method is used to add any new value to set data structure.
s={1,2,3}
print(id(s))
s.add(4)
print(s)
print(id(s))


Both id will be same, this proves that set is mutable data structure.

update() function: This function actually useful when we want to add all the elements of a sequence or more than one sequence into a single set.
s={1,2,3}
s.update([4,5])
print(s) # {1,2,3,4,5}

We can also pass more than one sequence in the update method.
s={1,2,3}
l1=[1,4,5]
l2=[6]
s.update(l1,l2)
print(s) # {1,2,3,4,5,6}


intersection() method: The return type of intersection method is a set. The simple example of usage of intersection method is given below.
s1={1,2,3}
s2={3,4,5}
s3=s1.intersection(s2)
print(s3) # {3}


union() method: As suggested by the name it will perform union operation between the two sets. Its return type is also a set.
s1={1,2,3}
s2={4,5,6}
s3=s1.union(s2)
print(s3) # {1,2,3,4,5,6} 


issubset() method: This function will tells us whether a given set is a subset of targeted set or not. Its return type is boolean.
s1={1,2,3}
s2={1,2}
print(s2.issubset(s1)) # True


issuperset() function: This method will tells us whether a given set is a superset of targeted set or  not. Its return type is also boolean.
s1={1,2,3}
s2={1,2}
print(s1.issuperset(s2)) # True



clear() function: This function is used to remove all the elements from the set data structure, means it will empty the targeted set.
s={1,2,3}
s.clear()
print(s) #set()


Be First to Post Comment !
Post a Comment