Sets & Set Operations: Uniqueness, Unions, Intersections & O(1) Membership
Overview & Learning Objectives
A set is an unordered collection of distinct, immutable objects implemented via a hash table without value payloads. In data analytics, sets are indispensable for deduplicating transactional streams, computing Venn diagram audience segments (retention, churn, overlap), and executing sub-millisecond membership testing on millions of IDs.
- Eliminate duplicate records instantly using set conversion.
- Execute mathematical set algebra: Union (`|`), Intersection (`&`), Difference (`-`), and Symmetric Difference (`^`).
- Compare performance between list search O(n) and set search O(1).
- Use `frozenset` when an immutable, hashable set is required as a dictionary key.
Industry Standard
Standard: AdTech and retention analytics at Spotify and Swiggy compute monthly active user overlaps and churn metrics directly through set intersections and set differences on customer UUID hashes.
Real-World Example: ScoopCraft Loyalty Cohort Segmentation
ScoopCraft analyzes active customers across Online App vs In-Store Parlour POS channels.
| Customer Cohort | Set Operation | Unique Count | Marketing Action |
|---|---|---|---|
| Omni-Channel Diners | App ∩ InStore (Intersection) | 4,500 | Enroll in Gold VIP Tier |
| App-Only Users | App - InStore (Difference) | 12,200 | Push In-Store Dining Voucher |
| In-Store Only Users | InStore - App (Difference) | 8,100 | SMS App Download Link with 20% Off |
| Total Unique Reach | App ∪ InStore (Union) | 24,800 | Target Audience for Brand Launch |
Functions & Methods Covered in this Chapter
Here is the definition, execution syntax, parameter breakdown, and real-world business example for each function/method covered in this chapter:
set.union(*others) / (s1 | s2)
Definition: Returns a new set containing all distinct elements from the original set and all specified iterables.
all_customers = loyal_custs | campaign_custs
*others: One or more sets or iterables to combine.
unique_audience = whatsapp_leads.union(sms_leads)set.intersection(*others) / (s1 & s2)
Definition: Returns a new set with elements common to the set and all others.
repeat_buyers = weekend_custs & weekday_custs
*others: Sets or iterables to check for shared elements.
loyal_diners = weekday_orders & weekend_ordersset.difference(*others) / (s1 - s2)
Definition: Returns a new set with elements in the original set that are not in the others.
churned_users = last_month_active - this_month_active
*others: Sets containing elements to exclude.
churned_custs = q1_active_users - q2_active_usersset.symmetric_difference(other) / (s1 ^ s2)
Definition: Returns a new set with elements in either the set or other but not in both.
single_channel_users = app_users ^ web_users
other: Another set to compare.
single_platform = mobile_app_users ^ web_portal_usersCommon Mistakes & Limitations
- Creating an empty set with `{}`: this initializes an empty dictionary! Always write `empty_set = set()`.
- Assuming sets preserve item ordering; although modern dicts preserve key order, sets are unordered hash tables.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Quick Unique Deduplication | list(set(items)) | list(set(items)) |
| Check Subset Relationship | s1.issubset(s2) | s1.issubset(s2) |
Pro Tips & Modern Best Practices
- If you need deduplication WHILE preserving original encounter order, use `list(dict.fromkeys(items))` (Python 3.7+).
- Use Bitsets or Bloom Filters when evaluating membership across billions of IDs in memory-constrained distributed pipelines.