What is a Set?
You've learned List, Tuple, and Dictionary. Set is the last data structure.
A set is a collection that has two special properties:
- No duplicate values — every item is unique
- No order — items have no index, no position
Looks similar to dictionary but no key-value pairs — just values.
The Killer Feature — No Duplicates
This is the main reason sets exist. When you need unique values — use a set.
Creating a Set
No Index — Cannot Access by Position
Sets have no order so there's no first or second item. You either loop through all items or check if something exists.
Checking Membership
Checking membership in a set is faster than in a list — especially with large data. This is one more reason to use sets when you only need to check existence.
Adding and Removing Items
Output:
{'apple', 'banana', 'mango', 'orange'}
{'apple', 'banana', 'mango', 'orange'}
{'apple', 'mango', 'orange'}
{'apple', 'mango', 'orange'}
Always prefer .discard() over .remove() unless you specifically want an error when item is missing.
Looping Through a Set
Works same as list but order is not guaranteed — items may print in any order every time you run.
Set Operations — The Real Power
Sets support mathematical set operations. These are extremely useful:
Union — All items from both sets
Intersection — Only items present in BOTH sets
Difference — Items in first set but NOT in second
Real World Use of Set Operations
Most Common Use Case — Remove Duplicates from List
In real projects this is the most frequent reason to use a set:
Output:
Original: ['python', 'coding', 'python', 'beginner', 'coding', 'python']
Unique: ['beginner', 'python', 'coding']
Convert to set to remove duplicates, convert back to list if you need indexing.
All Four Data Structures — Final Comparison
|
List |
Tuple |
Set |
Dictionary |
|
|
Ordered |
Yes |
Yes |
No |
Yes (Python 3.7+) |
|
Duplicates |
Yes |
Yes |
No |
Keys: No,
Values: Yes |
|
Changeable |
Yes |
No |
Yes |
Yes |
|
Access by |
Index |
Index |
— |
Key |
|
Syntax |
[] |
() |
{} |
{key:
val} |
Quick Decision Guide
Need to store data that won't change? → Tuple
Need unique values only? → Set
Need to look up data by a name/label? → Dictionary
Everything else (ordered, changeable list)? → List
Exercise 🏋️
Solve these three small problems using sets:
Problem 1 — Remove Duplicates
visitor_log = [101, 203, 101, 305, 203, 101, 407, 305]
Find how many unique visitors came. Print the unique visitor IDs.
Problem 2 — Common Friends
friends_a = {"Rahul", "Priya", "Gagan", "Amit", "Neha"}
friends_b = {"Priya", "Ravi", "Gagan", "Kiran", "Amit"}
Find:
- Friends common to both A and B
- Friends only A has (not B)
- All unique friends combined
Problem 3 — Membership Check
Ask user to enter a username. Check if it exists in this set of registered users and print appropriate message:
registered_users = {"gagan", "rahul", "priya", "amit", "neha"}
No comments:
Post a Comment