🔗 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

