π How to Join Sets in Python β Combine Data the Pythonic Way | TechTown.in
In Python, sets are designed for storing unique values. But what if you want to combine two or more sets?
Donβt worry β Python offers clean and efficient ways to join sets using built-in set operations like union(), update(), and operators like |.
In this guide, youβll learn all the ways to join sets in Python, with real-world examples and key differences between each method.
π¦ Letβs Create Two Example Sets
a = {"apple", "banana", "cherry"}
b = {"cherry", "date", "fig"}
π§ These sets share one common item: "cherry".
β
Method 1: set.union()
Returns a new set containing all unique items from both sets:
combined = a.union(b)
print(combined)
π― Output:
{'banana', 'cherry', 'fig', 'apple', 'date'}
β
Original sets a and b remain unchanged.
π Method 2: set.update()
Adds all items from another set to the current set (modifies in place):
a.update(b)
print(a)
π― Output:
{'banana', 'cherry', 'fig', 'apple', 'date'}
β οΈ a is now permanently changed. Use this when you want to modify the original set.
π£ Method 3: Using the | Operator
Another clean way to perform a union:
c = a | b
print(c)
π§ This is equivalent to a.union(b), and is preferred for quick one-liners.
π Join More Than Two Sets
You can join multiple sets using union() or chained | operators:
x = {"x1", "x2"}
y = {"y1", "y2"}
z = {"z1", "z2"}
joined = x.union(y, z)
# or
joined = x | y | z
π§ Real-World Example: Merging User Tags
user_tags_1 = {"python", "developer"}
user_tags_2 = {"blogger", "python"}
all_tags = user_tags_1.union(user_tags_2)
print(all_tags) # {'developer', 'python', 'blogger'}
β Great for eliminating duplicate tags in search systems or recommendation engines.
π Summary β Set Joining Methods in Python
| Method | Changes Original? | Returns New Set? | Notes |
|---|---|---|---|
a.union(b) | β No | β Yes | Best for keeping originals |
a.update(b) | β Yes | β No | Use when updating in place |
| `a | b` | β No | β Yes |
π Final Thoughts
Python gives you powerful tools to join sets without worrying about duplicates. Whether you’re merging user data, combining filters, or cleaning your dataset β using union() and update() makes your code faster, simpler, and more readable.
Use union() when you want to preserve original sets, and update() when you want to modify in place.
π Want to go deeper with Python sets? Visit TechTown.in