In this article, we will explain the set methods of Python one by one. The following is the list of built-in methods used in Python.
add() method
This method add() the required element in the
s = {2,4,6}
s.add(8)
print('Letters are:', s) #returns Letters are: {8, 2, 4, 6}
difference()
This removes all the elements from the set
x = {"apple", "banana", "mango"}
y = {"rose", "jasmine", "tulip"}
z = x.difference(y)
print(z) #returns {'apple', 'banana', 'mango'}
intersection()
It returns a set that is the intersection of two other sets.
a={"Ram", "Shyam", "Madhu"}
b={"Ram", "Sita", "Laksman"}
c=a.intersection(b)
print(c) #returns {'Ram'}
copy()
This method copies the set.
fruits = {"apple", "banana", "mango"}
x = fruits.copy()
print(x) #returns {'apple', 'banana', 'mango'}
isdisjoint()
This returns whether two sets have intersection or not. If there is intersection it returns true and if not it returns false.
a={"Ram", "Shyam", "Madhu"}
b={"Ram", "Sita", "Laksman"}
c=a.isdisjoint(b)
print(c) #returns False
intersection_update
This method removes the item that is not present in both the sets. It removes the unwanted item from the original set.
a={"Ram", "Shyam", "Madhu"}
b={"Ram", "Sita", "Laksman"}
a.intersection_update(b)
print(a) #returns {"Ram"}