Join Sets

Joining sets means combining elements from two or more sets. Because sets store unique values only, joining sets automatically removes duplicates.
Python supports multiple set operations for joining and comparing sets.

Join Sets Using Union (|)

The union operator combines all unique elements.
python
a = {1, 2, 3}
b = {3, 4, 5}

result = a | b
print(result)

Join Sets Using union()

Returns a new set containing all elements.
python
a = {1, 2, 3}
b = {3, 4, 5}

result = a.union(b)
print(result)

Join Multiple Sets

python
a = {1, 2}
b = {3, 4}
c = {5, 6}

result = a.union(b, c)
print(result)

Update Set with Another Set (update())

Modifies the original set.
python
a = {1, 2}
b = {3, 4}

a.update(b)
print(a)

Join Sets Using Loop

python
a = {1, 2}
b = {3, 4}

for item in b:
    a.add(item)

print(a)

Join Sets Using |= Operator

python
a = {1, 2}
b = {3, 4}

a |= b
print(a)

Join Sets with Different Data Types

python
a = {1, 2}
b = {"a", "b"}

print(a.union(b))

Join Frozen Sets

python
fs1 = frozenset([1, 2])
fs2 = frozenset([3, 4])

result = fs1 | fs2
print(result)
Frozen sets cannot be modified.

Common Mistakes

Expecting Order

python
result = {1, 3, 2}
print(result)
Order is not guaranteed.

Using + Operator

python
# a + b   # TypeError
Sets do not support concatenation.

Performance Note

  • Set union is very fast
  • Best used for deduplication
  • update() is efficient for large datasets

Summary

  • Sets join using union operations
  • | and union() create new sets
  • update() modifies existing set
  • Duplicates are removed automatically
  • Frozen sets support union but not modification