Python Sets 🚀
Python Sets is a core Python concept covering master Python Sets. Learn about unordered collections, removing duplicates, and mathematical operations like Union and Intersection with Venn diagrams. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Mentor's Note: Sets are like a high-security club. Once you're in, you're unique—no two people can have the same ID inside the club! 💡
🌟 The Scenario: The Guest List 🎫
Imagine you are the organizer of a massive party.
- The Logic:
- You have many friends coming. Even if someone says "I'm coming" three times, you only put their name on the list Once. 📦
- The names on the list don't have a special order; they are just a "Pile" of names. 📦
- You can easily check: "Is Ankit on the list?" ✅
- The Result: A clean, unique list of people without any duplicates. ✅
📖 Concept Explanation
1. What is a Set?
A set is a collection which is unordered, unchangeable*, and unindexed.
- Duplicate values are not allowed.
- Note: While you cannot change items, you can remove items and add new items.
2. Creating a Set
Sets are written with curly brackets {}.
myset = {"Apple", "Banana", "Cherry", "Apple"}
print(myset) # Output: {'Banana', 'Apple', 'Cherry'} (Apple appears only once!)
3. Why use a Set?
- Uniqueness: Automatically remove duplicates from a list.
- Math: Perform complex operations like finding common items between two groups.
🎨 Visual Logic: Set Operations (Venn Diagram)
[!TIP] ⭕ Visual Hint: Imagine two overlapping circles (A and B).
- UNION (
A | B): Everything in both circles. 🤝 - INTERSECTION (
A & B): Only the middle part where they overlap. 🎯 - DIFFERENCE (
A - B): Everything in A that is NOT in B. ✂️
💻 Implementation: The Set Lab
- Python (3.10+)
# 🛒 Scenario: Common Friends between two people
# 🚀 Action: Using intersection and union
vishnu_friends = {"Ankit", "John", "Sara"}
ankit_friends = {"Sara", "Peter", "Doe"}
# 🎯 1. Who do they BOTH know? (Intersection)
common = vishnu_friends.intersection(ankit_friends)
# 🤝 2. Everyone combined? (Union)
all_friends = vishnu_friends.union(ankit_friends)
# 🛍️ Outcome:
print(f"Common: {common}") # {'Sara'}
print(f"Total Unique: {len(all_friends)}") # 5
📊 Sample Dry Run (Removing Duplicates)
Input List: [1, 2, 2, 3]
| Step | Action | Logic | Resulting Set |
|---|---|---|---|
| 1 | Load 1 | Add to set | {1} |
| 2 | Load 2 | Add to set | {1, 2} |
| 3 | Load 2 | REJECTED ❌ | {1, 2} (Already exists) |
| 4 | Load 3 | Add to set | {1, 2, 3} |
📉 Complexity Analysis
- Adding/Removing: $O(1)$ - Extremely fast!
- Checking Existence (
in): $O(1)$ - Instant, compared to $O(n)$ for Lists. ⚡
🎯 Practice Lab 🧪
Task: You have a list of employee IDs: [101, 102, 101, 103, 102]. Write a program to find how many unique employees are there.
Hint: len(set(your_list)). 💡
🔗 Related Topics
← Back: Tuples | Next: Dictionaries →