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
3. update() – Add Many Items
Adds multiple items from list, tuple, or another set.
Example
4. remove() – Remove Item (Error if Missing)
Removes a specific item.
Example
❌ Error if item not found.
5. discard() – Remove Item Safely
Removes item without error, even if missing.
Example
6. pop() – Remove Random Item
Removes and returns a random item.
Example
7. clear() – Remove All Items
Removes all items from the set.
Example
8. union() – Join Sets
Returns a new set with all unique items.
Example
9. intersection() – Common Items
Returns items present in both sets.
Example
10. difference() – Items Not Common
Returns items in first set but not in second.
Example
11. issubset() – Check Subset
Checks if all items are inside another set.
Example
12. issuperset() – Check Superset
Example
13. isdisjoint() – No Common Items
Example
14. Common Beginner Mistakes
❌ Using Index
❌ Error.
❌ Using + to Join Sets
❌ Error.
15. Simple Practice Examples
Example 1: Remove Duplicates
Example 2: Common Numbers
Example 3: Clear Set
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 😊
