In Python, you can join (combine) sets to create a new set that contains all unique elements from the given sets. The most common ways to join sets are:
union() method| (pipe) operatorupdate() method to modify an existing set in placeunion() returns a new set and does not change the original sets.| operator is a shorthand way of doing union.update() adds all elements from another set (or iterable) into the original set.result = set1.union(set2)result = set1 | set2set1.update(set2)union() and |
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Using union()
joined_set = set1.union(set2)
print(joined_set) # {1, 2, 3, 4, 5}
# Using |
joined_set2 = set1 | set2
print(joined_set2) # {1, 2, 3, 4, 5}
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Update set1 with all elements of set2
set1.update(set2)
print(set1) # {1, 2, 3, 4, 5}
In the first example, set1.union(set2) and set1 | set2 both create a new set containing all unique elements from set1 and set2.
The output will look like:
{1, 2, 3, 4, 5}
In the second example, set1.update(set2) modifies set1 directly. After the update, set1 becomes:
{1, 2, 3, 4, 5}
Notice how the duplicate element 3 appears only once in the final set, because sets automatically remove duplicates.
union() when you need a new combined set without changing the originals.update() when you want to add elements directly into an existing set.update(), not just another set.union(). Print the result.| operator and compare the output.update() with a list of new values. Check how the set changes.