T
Tech Town
Log InSign Up Free
← Back to Blog

June 19, 2025 · admin

Join Sets


πŸ”— 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

MethodChanges Original?Returns New Set?Notes
a.union(b)❌ Noβœ… YesBest for keeping originals
a.update(b)βœ… Yes❌ NoUse when updating in place
`ab`❌ 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