Sets can be joined in Python in a number of different ways. For instance, update()
adds all the elements of one set to the other. Similarly, union()
combines all the elements of the two sets and returns them in a new set. Both union()
and update()
operations exclude duplicate elements.
union()
set1 = {1, 2 , 3}set2 = {4, 5, 6}set_union = set1.union(set2)print(set_union)
Lines 1–5: The union operation returns a new set, set_union
, containing all the items from the previous 2 sets, set1
, set2
.
update()
set1 = {1, 2 , 3}set2 = {4, 5, 6}set1.update(set2)print(set1)
Lines 1–5: The update method adds the values of set2
into set1
.
intersection_update()
and intersection()
methodsThere are also some methods that keep only duplicates. These are intersection_update()
and intersection()
.
The intersection_update()
method only stores the items that are present in both sets. While the intersection()
method returns a new set containing items that are present in both sets.
intersection_update()
set1 = {"apple", "mango", "cherry"}set2 = {"strawberry", "mango", "apple"}set1.intersection_update(set2)print(set1)
Lines 1–6: The intersection_update()
only keeps those items in set1
that are present in both sets.
intersection()
set1 = {"apple", "mango", "cherry"}set2 = {"strawberry", "mango", "apple"}set3 = set1.intersection(set2)print(set3)
Lines 1–6: The intersection()
method returns a new set, set3
, that contains values that are present in both the previous sets.
symmetric_difference_update()
and symmetric_difference()
methodAnother way of joining sets is by keeping all the elements except duplicates. For this operation we use symmetric_difference_update()
and symmetric_difference()
method.
The symmetric_difference_update() method
stores only the elements that are not present in both sets. While symmetric_difference()
stores only the elements that are not present in both sets in the new set and returns it.
symmetric_difference_update()
set1 = {"apple", "mango", "cherry"}set2 = {"strawberry", "mango", "apple"}set1.symmetric_difference_update(set2)print(set1)
Lines 1–6: We use symmetric_difference_update()
to store those values in set1
that are not present in both sets.
symmetric_difference()
set1 = {"apple", "mango", "cherry"}set2 = {"strawberry", "mango", "apple"}set3 = set1.symmetric_difference(set2)print(set3)
Lines 1–6: We use symmetric_difference()
to return a new set set3
that only stores those values that are not present in the previous 2 sets.