Python Sets & Mathematical Operations
A set (set) in Python is an unordered collection of unique, immutable elements enclosed in curly braces ({...}).
- No Duplicates Allowed: Duplicate elements are automatically discarded upon insertion.
- Unordered: Elements do not maintain positional index order (you cannot access
s[0]). - Empty Set Syntax: To create an empty set, you MUST write
s = set(). Writing{}creates an empty dictionary!
# 1. Creating a set with duplicate values (duplicates automatically removed!)
numbers_set = {1, 2, 2, 3, 4, 4, 5}
print("Numbers Set (Unique):", numbers_set)
# 2. Instant list deduplication in ONE step:
raw_emails = ["alex@test.com", "balaji@test.com", "alex@test.com", "chloe@test.com"]
unique_emails = list(set(raw_emails))
print("\nOriginal emails count:", len(raw_emails))
print("Unique emails list: ", unique_emails)
# 3. Empty set vs Empty dict:
empty_s = set() # Set!
empty_d = {} # Dict!
print("\nType of set():", type(empty_s).__name__)
print("Type of {}: ", type(empty_d).__name__)
Deduplicating a 100,000-item list with list(set(items)) executes in linear $O(N)$ time instead of slow $O(N^2)$ nested loops.
Add and remove elements dynamically:
set.add(elem): Adds a single element.set.update(iterable): Merges multiple elements from a list or set.set.remove(elem): Removes element; raisesKeyErrorif missing!set.discard(elem): Safe removal β removes element if present without raising an error if missing!
skills = {"Python", "Git"}
print("Initial skills:", skills)
# 1. add() a single item
skills.add("Docker")
# 2. update() with a list of multiple items
skills.update(["FastAPI", "PostgreSQL"])
print("After adding skills:", skills)
# 3. discard() vs remove()
skills.discard("Java") # Safe! Does not crash even though 'Java' is not in set
skills.remove("Git") # Removes 'Git' cleanly
print("After removals:", skills)
Always prefer .discard() over .remove() when deleting elements unless you explicitly want your program to crash if the element is missing.
Python sets implement full mathematical Venn diagram operations using operator symbols or method names:
dev_frontend = {"HTML", "CSS", "JavaScript", "React", "Git"}
dev_backend = {"Python", "FastAPI", "PostgreSQL", "React", "Git"}
# 1. Union (|): All skills across both developers
all_skills = dev_frontend | dev_backend
print("1. Union (All unique skills):", all_skills)
# 2. Intersection (&): Skills shared by BOTH developers
shared_skills = dev_frontend & dev_backend
print("2. Intersection (Shared skills):", shared_skills)
# 3. Difference (-): Frontend skills NOT known by Backend developer
frontend_only = dev_frontend - dev_backend
print("3. Difference (Frontend only):", frontend_only)
# 4. Symmetric Difference (^): Skills unique to EITHER developer (excluding shared)
unique_to_each = dev_frontend ^ dev_backend
print("4. Symmetric Diff (Non-shared):", unique_to_each)
- Shared skills:
{'React', 'Git'}. - Frontend only:
{'HTML', 'CSS', 'JavaScript'}. - Union:
{'HTML', 'CSS', 'JavaScript', 'React', 'Git', 'Python', 'FastAPI', 'PostgreSQL'}.
Check relationships between multiple groups of data:
A.issubset(B)(orA <= B): ReturnsTrueif all elements of A are in B.A.issuperset(B)(orA >= B): ReturnsTrueif A contains all elements of B.A.isdisjoint(B): ReturnsTrueif A and B have zero elements in common.
admin_permissions = {"read", "write", "delete", "deploy"}
guest_permissions = {"read"}
billing_permissions = {"view_invoice", "pay_bill"}
print("Is guest a subset of admin?", guest_permissions.issubset(admin_permissions)) # True
print("Is admin a superset of guest?", admin_permissions.issuperset(guest_permissions)) # True
print("Are admin and billing disjoint (no overlap)?", admin_permissions.isdisjoint(billing_permissions)) # True
Role-Based Access Control (RBAC) in web servers uses required_roles.issubset(user_roles) to grant or deny route access instantly.
Set elements MUST be hashable and immutable. Adding a list to a set (e.g. {1, [2, 3]}) raises TypeError: unhashable type: 'list'. Store tuples instead: {1, (2, 3)}.
Find the common elements (Intersection) and unique elements (Symmetric Difference) between two lists of lottery numbers.
ticket_a = {7, 14, 21, 28, 35}
ticket_b = {14, 28, 42, 49, 56}
print("Ticket A:", ticket_a)
print("Ticket B:", ticket_b)
print("Matched Winning Numbers (Intersection):", ticket_a & ticket_b)
print("Unique to One Ticket (Symmetric Diff):", ticket_a ^ ticket_b)
Q Why are sets faster than lists for checking membership (in)?
Checking "x in list" requires linear O(N) scanning through all elements. Checking "x in set" computes the hash of x and jumps directly to that memory bucket in instantaneous O(1) constant time.
Q What is a frozenset in Python?
A frozenset is an immutable version of a set. Once created, elements cannot be added or removed. Because it is immutable and hashable, a frozenset can be stored inside another set or used as a dictionary key.
Q Can sets contain duplicate items?
No. Sets mathematically enforce element uniqueness. Any duplicate value added to a set is silently discarded.