Python Sets πΒΆ
Prerequisites: Python Lists
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. βοΈ
graph TD
subgraph Union: ["A βͺ B"]
U[Everything]
end
subgraph Intersection: ["A β© B"]
I[Common Items Only]
end
π» Implementation: The Set LabΒΆ
# π 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: The Unique ID Filter
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)). π‘
β Back: Tuples | Next: Dictionaries β