Python – Set Methods

1. What are Set Methods?

Set methods are built-in functions that help us work easily with sets.

Sets are used to:

  • Store unique values

  • Remove duplicates

  • Do math-like operations (union, intersection)

2. add() – Add One Item

Adds one item to a set.

Example

fruits = {"apple", "banana"}
fruits.add("orange")
print(fruits)

3. update() – Add Many Items

Adds multiple items from list, tuple, or another set.

Example

fruits.update(["mango", "grape"])
print(fruits)

4. remove() – Remove Item (Error if Missing)

Removes a specific item.

Example

fruits.remove("banana")
print(fruits)

❌ Error if item not found.

5. discard() – Remove Item Safely

Removes item without error, even if missing.

Example

fruits.discard("banana")

6. pop() – Remove Random Item

Removes and returns a random item.

Example

item = fruits.pop()
print(item)
print(fruits)

7. clear() – Remove All Items

Removes all items from the set.

Example

fruits.clear()
print(fruits)

8. union() – Join Sets

Returns a new set with all unique items.

Example

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

print(a.union(b))

9. intersection() – Common Items

Returns items present in both sets.

Example

print(a.intersection(b))

10. difference() – Items Not Common

Returns items in first set but not in second.

Example

print(a.difference(b))

11. issubset() – Check Subset

Checks if all items are inside another set.

Example

x = {1, 2}
y = {1, 2, 3}

print(x.issubset(y))

12. issuperset() – Check Superset

Example

print(y.issuperset(x))

13. isdisjoint() – No Common Items

Example

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

print(a.isdisjoint(b))

14. Common Beginner Mistakes

❌ Using Index

print(fruits[0])

❌ Error.

❌ Using + to Join Sets

a + b

❌ Error.

15. Simple Practice Examples

Example 1: Remove Duplicates

data = [1, 2, 2, 3]
unique = set(data)
print(unique)

Example 2: Common Numbers

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

print(a.intersection(b))

Example 3: Clear Set

items = {"pen", "book"}
items.clear()
print(items)

16. Summary (Set Methods)

add() and update() add items
remove() and discard() delete items
union() joins sets
intersection() finds common
✔ Sets store unique values

📘 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 Exercises

  • Dictionary Basics

  • Dictionary Methods

  • Dictionary Exercises

Just tell me 😊

You may also like...