Python provides several ways to join two or more sets.
The union() function joins two sets.
When you use the union() function to join sets, it returns a new set containing all the unique elements from the both sets.
colors_set_1 = {"Red", "Blue"}
colors_set_2 = {"Green"}
colors_set_3 = colors_set_1.union(colors_set_2)
print(colors_set_3)
{'Red', 'Blue', 'Green'}
In the above example, we are joining two different sets using the union() function and assigning those join sets to another set variable. Accordingly, both sets' unique items are present in the third join set.
To join sets, you can use the update() function, which adds all items from one set to another set.
colors_set_1 = {"Red", "Blue"}
colors_set_2 = {"Green"}
colors_set_1.update(colors_set_2)
print(colors_set_1)
{'Blue', 'Red', 'Green'}
Using the update() function, we are joining colors_set_2 with colors_set_1, so you can see in the output that colors_set_2 items appear in colors_set_1.
Using the intersection_update() function, you can select only similar items from two sets.
colors_set_1 = {"Red", "Blue"}
colors_set_2 = {"Red", "Green"}
colors_set_1.intersection_update(colors_set_2)
print(colors_set_1)
{'Red'}
In the above example, we are joining two different color sets using the intersection_update() function, and in the output, we get a "Red" color because the "Red" color is similar in both sets.
You can also use the intersection() function to select only similar items from two sets. When you use the intersection() function, it returns a new set.
colors_set_1 = {"Red", "Blue"}
colors_set_2 = {"Red", "Green"}
colors_set_3 = colors_set_1.intersection(colors_set_2)
print(colors_set_3)
{'Red'}
We are joining two different color sets using the intersection() function, but we get all similar items in the new set.
A symmetric_difference_update() function selects only non-similar items from two sets and ignores similar items.
colors_set_1 = {"Red", "Blue"}
colors_set_2 = {"Red", "Green"}
colors_set_1.symmetric_difference_update(colors_set_2)
print(colors_set_1)
{'Blue', 'Green'}
In the above example, we are joining two different color sets using the symmetric_difference_update() function, and in the output, we get non-similar items from both sets.
You can also use the symmetric_difference() function to ignore similar items from two sets. When you use the symmetric_difference() function, it returns a new set.
colors_set_1 = {"Red", "Blue"}
colors_set_2 = {"Red", "Green"}
colors_set_3 = colors_set_1.symmetric_difference(colors_set_2)
print(colors_set_3)
{'Blue', 'Green'}
symmetric_difference() function, but we get all non-similar items in the new set.