Python Sets & Mathematical Operations

🐍 Python 3.12+ 🟒 Chapter 14 of 65 πŸ“‚ Phase 3: Strings and Collections πŸ“… 2026 Edition
πŸ“Œ Covered in this chapter: Unordered Unique Elements Β· Hash Set Internals Β· Adding/Removing Β· Union Β· Intersection Β· Difference Β· Symmetric Diff
Master Python sets: deduplication, hash set internals, adding/removing items, mathematical set operations (Union, Intersection, Difference, Symmetric Difference), and Set vs List performance.
1What is a Set? Uniqueness & Instant Deduplication

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!
πŸ’» Example 1: Creating Sets and Deduplicating Lists
# 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__)
πŸ” Performance Advantage:

Deduplicating a 100,000-item list with list(set(items)) executes in linear $O(N)$ time instead of slow $O(N^2)$ nested loops.

2Modifying Sets: add(), update(), remove() vs discard()

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; raises KeyError if missing!
  • set.discard(elem): Safe removal β€” removes element if present without raising an error if missing!
πŸ’» Example 2: Adding and Removing Elements from Sets
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)
πŸ” Pro Tip:

Always prefer .discard() over .remove() when deleting elements unless you explicitly want your program to crash if the element is missing.

3Mathematical Set Operations (Union, Intersection, Difference, Symmetric Diff)

Python sets implement full mathematical Venn diagram operations using operator symbols or method names:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Set Operation β”‚ Operator β”‚ Method Equivalent β”‚ Description β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Union β”‚ A | B β”‚ A.union(B) β”‚ All items in A OR B β”‚ β”‚ Intersection β”‚ A & B β”‚ A.intersection(B) β”‚ Common items in BOTH A AND B β”‚ β”‚ Difference β”‚ A - B β”‚ A.difference(B) β”‚ Items in A that are NOT in B β”‚ β”‚ Symmetric Difference β”‚ A ^ B β”‚ A.symmetric_diff(B) β”‚ Items in EITHER A or B, not bothβ”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
πŸ’» Example 3: Mathematical Set Operations in Action
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)
πŸ” Venn Diagram Breakdown:
  • Shared skills: {'React', 'Git'}.
  • Frontend only: {'HTML', 'CSS', 'JavaScript'}.
  • Union: {'HTML', 'CSS', 'JavaScript', 'React', 'Git', 'Python', 'FastAPI', 'PostgreSQL'}.
4Set Relationships: Subsets, Supersets & Disjoint Sets

Check relationships between multiple groups of data:

  • A.issubset(B) (or A <= B): Returns True if all elements of A are in B.
  • A.issuperset(B) (or A >= B): Returns True if A contains all elements of B.
  • A.isdisjoint(B): Returns True if A and B have zero elements in common.
πŸ’» Example 4: Testing Subsets, Supersets, and Disjoint Sets
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
πŸ” Practical Security Use Case:

Role-Based Access Control (RBAC) in web servers uses required_roles.issubset(user_roles) to grant or deny route access instantly.

⚠️ Common Developer Pitfall: Attempting to Store Mutable Objects in a Set

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)}.

πŸ’» Hands-on Interactive Practice Challenge

Find the common elements (Intersection) and unique elements (Symmetric Difference) between two lists of lottery numbers.

Python 3 Practice Challenge β–Ά Run in Compiler
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)
Run This Challenge in Online Python IDE β†’
❓ Frequently Asked Questions (FAQ)

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.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime Β· Last updated August 2026