Sets (Uniqueness & Set Operations)
Sets are the ultimate tool when you need to remove duplicate entries and perform mathematical operations like unions and intersections.
What is it?
A Python `set` is an unordered collection of unique, hashable elements enclosed in curly braces `{item1, item2}`.
Why is it used?
Instantly eliminates duplicates from lists and provides O(1) constant-time membership lookups.
Detailed Explanation
Set Mathematics:
• Union (`|` or `.union()`): All unique items from both sets.
• Intersection (`&` or `.intersection()`): Only items present in both sets.
• Difference (`-` or `.difference()`): Items in Set A that are NOT in Set B.
• Symmetric Difference (`^`): Items in either set, but not both.
• Quick deduplication: `unique_list = list(set(duplicate_list))`.
Syntax Structure
Syntax Blueprint
my_set = {1, 2, 3, 3, 2} # Result: {1, 2, 3}
common = set_a & set_b # Intersection
Code Example
PYTHON Code
# Student Course Enrollments
python_batch = {"Rohan", "Sneha", "Amit", "Karan"}
data_analytics_batch = {"Sneha", "Karan", "Pooja", "Vikram"}
# 1. Intersection (&): Students enrolled in BOTH batches
both_courses = python_batch & data_analytics_batch
print("Students in both courses:", both_courses)
# 2. Union (|): All distinct enrolled students
all_unique_students = python_batch | data_analytics_batch
print("Total unique students: ", len(all_unique_students))
# 3. Difference (-): Students in Python ONLY
python_only = python_batch - data_analytics_batch
print("Python only students: ", python_only)
# 4. Instant List Deduplication
raw_tags = ["python", "coding", "flask", "python", "web", "flask"]
unique_tags = list(set(raw_tags))
print("Deduplicated tags: ", unique_tags)
Explanation of the Code
• `&` finds students taking both courses.
• `|` combines rosters with automatic duplicate elimination.
• `list(set(...))` deduplicates lists in a single readable line.
Expected Output
Students in both courses: {'Sneha', 'Karan'}
Total unique students: 6
Python only students: {'Rohan', 'Amit'}
Deduplicated tags: ['python', 'coding', 'web', 'flask']
Real-World Application
Used across databases and access control to find mutual friends, common interests, and eliminate duplicate email subscriptions.
Common Mistakes to Avoid
• Creating an empty set with `{}` (that creates an empty dictionary!). Use `empty_set = set()`.
• Assuming sets maintain insertion order (sets are inherently unordered).
Quick Practice Challenge
Given two sets `a = {1, 2, 3}` and `b = {3, 4, 5}`, find elements present in `a` but not in `b`.
Key Takeaways
• Sets only store unique elements.
• Create empty set with `set()`, not `{}`.
• Use `&` for intersection and `|` for union.