Python – Join Sets

1. What Does β€œJoin Sets” Mean?

Joining sets means combining two or more sets.

Remember:
πŸ‘‰ Sets store only unique values
πŸ‘‰ Duplicate values are removed automatically

2. Join Sets Using union()

union() combines all items from both sets.

Example

set1 = {1, 2, 3}
set2 = {3, 4, 5}

result = set1.union(set2)
print(result)

Output:

{1, 2, 3, 4, 5}

3. Join Sets Using | Operator

This is a short way to join sets.

Example

a = {"apple", "banana"}
b = {"banana", "orange"}

print(a | b)

4. Join Multiple Sets

Example

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

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

5. Join Set with List or Tuple

union() can join different data types.

Example

numbers = {1, 2}
more = [2, 3, 4]

result = numbers.union(more)
print(result)

6. Update One Set Using update()

update() adds items to the same set.

Example

a = {10, 20}
b = {20, 30}

a.update(b)
print(a)

7. Difference Between union() and update()

Method Creates New Set Changes Original
union() βœ” Yes ❌ No
update() ❌ No βœ” Yes

8. Common Beginner Mistakes

❌ Expecting Duplicate Values

{1, 2}.union({2, 3})

Duplicates are removed automatically.

❌ Using + Operator

set1 + set2

❌ Error: sets do not support +.

9. Simple Practice Examples

Example 1: Join City Sets

cities1 = {"Delhi", "Mumbai"}
cities2 = {"Kolkata", "Mumbai"}

all_cities = cities1.union(cities2)
print(all_cities)

Example 2: Use |

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

print(a | b)

Example 3: Update Set

nums = {1, 2}
nums.update({3, 4})
print(nums)

10. Summary (Join Sets)

βœ” Use union() to create new set
βœ” Use | for short join
βœ” Use update() to change same set
βœ” Duplicate values removed
βœ” Sets store unique data

πŸ“˜ Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Set Methods (full)

  • Set Exercises

  • Dictionaries (easy)

  • Dictionary Methods

Just tell me 😊

You may also like...