1. add( ) method :
The add( ) method inserts one element into the set
If the value is already present , it is ignored .
Python
fruits = {"apple", "banana"} fruits.add("mango") print(fruits) #output {'apple', 'banana', 'mango'} #order may change2. update( ) method :
The update method can add multiple values from lists, tuples, another set etc.
Python
numbers = {1, 2, 3} numbers.update([4, 5, 6]) print(numbers) #output {1, 2, 3, 4, 5, 6} 3. remove( ) method :
remove( ) deletes the given element.
If the item does not exist, it will throw error
Python
fruits = {"apple", "banana", "mango"} fruits.remove("banana") print(fruits) #output {'apple', 'mango'} 4. discard( ) method :
Removes the item only if it exists.
If the item does not exist, no error is occured.
Python
numbers = {1, 2, 3} numbers.discard(2) print(numbers) #output {1, 3} 5. pop( ) method :
Since sets are unordered , pop( ) removes any arbitary element.
Python
colors = {"red", "blue", "green"} item = colors.pop() print(colors) print("Removed:", item) #output Removed: green #Output may vary 6. clear( ) method :
Deletes all the elements , but keeps the set object.
Python
data = {10, 20, 30} data.clear() print(data) #output set()6. del :
Deletes the entire set object.
Python
numbers = {1, 2, 3} del numbers print(numbers) #output Name Error7. Union( ) :
The union() method combines elements from both sets and returns a new set.
Python
a = {1, 2, 3} b = {3, 4, 5} result = a.union(b) print(result) #output {1, 2, 3, 4, 5}8. intersection( ) :
Returns a new set by keeping only elements that are common in both the sets.
intersection_update( ) is similar to intersection( ) but it will change the original set instead of returning a new set.
Python
set1 = {"apple", "banana", "cherry"} set2 = {"google", "microsoft", "apple"} set3 = set1.intersection(set2) print(set3) #output {'apple'}9. difference( ) :
Will return a new set that will contain only the items from the first set that are not present in the other set.
difference_update( ) is similar to difference( ) but it will change the original set instead of returning a new set.
Python
set1 = {"apple", "banana", "cherry"} set2 = {"google", "microsoft", "apple"} set3 = set1.difference(set2) print(set3) #output {'banana', 'cherry'}10. symmetric_difference( ) :
This method will keep only the elements that are NOT present in both sets.
symmetric_difference_update( ) is similar to symmetric_difference( ) but it will change the original set instead of returning a new set.
Python
set1 = {"apple", "banana", "cherry"} set2 = {"google", "microsoft", "apple"} set3 = set1.symmetric_difference(set2) print(set3) #output {'google', 'banana', 'microsoft', 'cherry'} 11. copy( ) :
Creates a duplicate set
Python
a = {1, 2, 3} b = a.copy() print(b) #output {1, 2, 3}