Joining sets helps to combine values, removes duplicates automatically .
1. 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}2. update( ) :
Unlike union() , update( ) method modifies the original set.
Python
a = {1, 2, 3} b = {3, 4, 5} a.update(b) print(a) #output {1, 2, 3, 4, 5} 3. 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'} 4. 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'} 5. 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'}