Python Sets ๐¶
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 โ