Skip to content

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 โ†’