Sets
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements.
Example - 1:
s1 = { 1,1,1,1,1,1,1,1,1,2,3,4,5}
s2 = { 4,5,6,7,8}
print("Set1 = ",s1)
print("Set2 = ",s2)
Set1 = {1, 2, 3, 4, 5}
Set2 = {4, 5, 6, 7, 8}
Methods for sets
Example - 2:
#union -> Returns a union of two set.Using the ‘|’ operator between 2 sets is the same as writing set1.union(set2)
#intersection -> Returns an intersection of two sets.The ‘&’ operator comes can also be used in this case.
#Difference -> Returns a set containing all the elements of invoking set but not of the second set. We can use ‘-‘ operator here.
print("Union of s1 and s2 = ",s1.union(s2))
print("Intersection of s1 and s2 = ",s1.intersection(s2))
print("Difference of s1 with s2 = ",s1.difference(s2))
Union of s1 and s2 = {1, 2, 3, 4, 5, 6, 7, 8}
Intersection of s1 and s2 = {4, 5}
Difference of s1 with s2 = {1, 2, 3}
Example - 3:
#add -> Adds the item x to set if it is not already present in the set.
people = {"Jay", "Idrish", "Archil"}
people.add("Daxit")
print(people)
{'Archil', 'Jay', 'Idrish', 'Daxit'}
Last updated
Was this helpful?