Python for Data Analytics & AutomationLesson 10 of 41
Lesson 10 of 41

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 CohortSet OperationUnique CountMarketing Action
Omni-Channel DinersApp ∩ InStore (Intersection)4,500Enroll in Gold VIP Tier
App-Only UsersApp - InStore (Difference)12,200Push In-Store Dining Voucher
In-Store Only UsersInStore - App (Difference)8,100SMS App Download Link with 20% Off
Total Unique ReachApp ∪ InStore (Union)24,800Target 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:

Function 1

set.union(*others) / (s1 | s2)

Definition: Returns a new set containing all distinct elements from the original set and all specified iterables.

Syntax / Code Pattern:
all_customers = loyal_custs | campaign_custs
Parameters Breakdown:
  • *others: One or more sets or iterables to combine.
Real-World Example (Total Reach Across Marketing Channels):
Problem / Scenario: Find all unique customer phone numbers targeted across WhatsApp and SMS campaigns.
Code / Expression: unique_audience = whatsapp_leads.union(sms_leads)
Result: {"9876543210", "9812345678", "9900112233"}
Why it works: Combines both customer lists while automatically removing duplicate phone numbers.
Function 2

set.intersection(*others) / (s1 & s2)

Definition: Returns a new set with elements common to the set and all others.

Syntax / Code Pattern:
repeat_buyers = weekend_custs & weekday_custs
Parameters Breakdown:
  • *others: Sets or iterables to check for shared elements.
Real-World Example (Identifying High-Frequency Loyalists):
Problem / Scenario: Find customers who ordered on BOTH weekdays and weekends.
Code / Expression: loyal_diners = weekday_orders & weekend_orders
Result: {"CUST_401", "CUST_708"}
Why it works: Keeps only customer IDs present in both customer sets.
Function 3

set.difference(*others) / (s1 - s2)

Definition: Returns a new set with elements in the original set that are not in the others.

Syntax / Code Pattern:
churned_users = last_month_active - this_month_active
Parameters Breakdown:
  • *others: Sets containing elements to exclude.
Real-World Example (Churned Customer Analysis):
Problem / Scenario: Identify active customers from Q1 who did not place an order in Q2.
Code / Expression: churned_custs = q1_active_users - q2_active_users
Result: {"CUST_102", "CUST_205"}
Why it works: Subtracts Q2 active users from Q1 active users, leaving only non-returning accounts.
Function 4

set.symmetric_difference(other) / (s1 ^ s2)

Definition: Returns a new set with elements in either the set or other but not in both.

Syntax / Code Pattern:
single_channel_users = app_users ^ web_users
Parameters Breakdown:
  • other: Another set to compare.
Real-World Example (Single-Platform User Segmentation):
Problem / Scenario: Find users who only use App OR Web, but not both channels.
Code / Expression: single_platform = mobile_app_users ^ web_portal_users
Result: {"USER_99", "USER_104"}
Why it works: Discards omni-channel shoppers, isolating exclusive app-only and web-only users.

Common 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)

ActionWindowsMac
Quick Unique Deduplicationlist(set(items))list(set(items))
Check Subset Relationships1.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.
Sets & Set Operations: Uniqueness, Unions, | DataCliq