Python Sets
1. What is a Set?
A set is a collection of items that is:
-
Unordered
-
No duplicate values
-
Changeable
In simple words:
👉 A set stores unique values only.
2. Creating a Set
Sets are written using curly brackets { }.
Example
3. Duplicate Values Are Not Allowed
Example
Output:
4. Set is Unordered
Items have no fixed order.
Example
Output order may change.
5. Access Set Items (Using Loop)
You cannot access items by index.
Example
6. Check Item Exists
Example
7. Add Items to a Set
Add One Item (add())
Add Multiple Items (update())
8. Remove Items from a Set
Remove Item (remove())
❌ Error if item not found.
Remove Safely (discard())
Remove Random Item (pop())
9. Set Length
Example
10. Join Sets
Union (|)
Intersection (&)
Difference (-)
11. Set Methods (Common)
| Method | Use |
|---|---|
add() |
Add one item |
update() |
Add many items |
remove() |
Remove item |
discard() |
Remove safely |
clear() |
Remove all items |
12. Common Beginner Mistakes
❌ Creating Empty Set Wrong Way
This creates a dictionary.
✔ Correct:
❌ Using Index
❌ Error.
13. Simple Practice Examples
Example 1: Unique Numbers
Example 2: Check Membership
Example 3: Remove Duplicates
14. Summary (Python Sets)
✔ Stores unique values
✔ No duplicate allowed
✔ Unordered
✔ No index access
✔ Useful for removing duplicates
📘 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 Exercises
Just tell me 😊
