Python Join Sets

In Python, you can join two or more sets using various methods. Joining sets combines their elements, removing any duplicates.

1. Using union() – Returns a New Set

set1 = {"apple", "banana"}
set2 = {"cherry", "banana"}
result = set1.union(set2)
print(result)

Output:

{'apple', 'banana', 'cherry'}

union() combines sets without modifying the originals.

2. Using update() – Modifies the Set in Place

set1 = {"a", "b"}
set2 = {"c", "d"}
set1.update(set2)
print(set1)

Output:

{'a', 'b', 'c', 'd'}

update() adds all items from another set (or iterable) into the original set.

3. Using | Operator – Set Union

a = {1, 2}
b = {2, 3}
print(a | b)

Output:

{1, 2, 3}

➕ The pipe symbol | acts as a union operator.

4. Join More Than Two Sets

set1 = {"a"}
set2 = {"b"}
set3 = {"c"}
result = set1.union(set2, set3)
print(result)

Output:

{'a', 'b', 'c'}

You can join multiple sets in one call using union().

5. Join Set with Other Iterables (List, Tuple)

a = {"x", "y"}
b = ["y", "z"]
a.update(b)
print(a)

Output:

{'x', 'y', 'z'}

update() accepts any iterable (lists, tuples, sets, etc.).

6. Chained Union with |

a = {1}
b = {2}
c = {3}
print(a | b | c)

Output:

{1, 2, 3}

Use chained | to combine multiple sets quickly.

Summary Table

MethodDescriptionModifies Original Set
union()Combines sets, returns new set❌ No
update()Adds elements to current set✅ Yes
`` operatorUnion of sets

⚠️ Important Notes:

  • Duplicates are automatically removed.
  • Sets are unordered; the join order doesn’t matter