CS Pathfinder Logo CS Pathfinder

Unit 5 · Advanced Topics

Set Operations and Methods

Master all set operations — union, intersection, difference, symmetric difference — along with built-in methods like add(), remove(), discard(), and subset/superset checks.

Table of Contents

Union (|)

University Definition

The union of two sets returns a new set containing all elements from both sets (without duplicates). It can be performed using the | operator or the union() method.

Venn Diagram Analogy

    Set A         Set B
   {1,2,3}       {3,4,5}
    __|____________|__
   |  A     |     B  |
   | 1,2    |   4,5  |
   |     3  |        |
   |________|________|
   
   Union = A | B = {1,2,3,4,5}
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# Using | operator
union_result = set_a | set_b
print("A | B:", union_result)

# Using union() method
union_method = set_a.union(set_b)
print("A.union(B):", union_method)

# Union with multiple sets
set_c = {7, 8}
multi_union = set_a.union(set_b, set_c)
print("A | B | C:", multi_union)

# Union with a list
union_list = set_a.union([5, 6, 7])
print("A | list:", union_list)

# Practical: combining class rosters
class1 = {"Rahul", "Priya", "Amit"}
class2 = {"Neha", "Rohan", "Priya"}
class3 = {"Amit", "Sneha", "Rahul"}

all_students = class1 | class2 | class3
print("All unique students:", all_students)
print("Total unique:", len(all_students))

Output:

A | B: {1, 2, 3, 4, 5, 6}
A.union(B): {1, 2, 3, 4, 5, 6}
A | B | C: {1, 2, 3, 4, 5, 6, 7, 8}
A | list: {1, 2, 3, 4, 5, 6, 7}
All unique students: {'Rahul', 'Priya', 'Amit', 'Neha', 'Rohan', 'Sneha'}
Total unique: 6

Intersection (&)

University Definition

The intersection of two sets returns a new set containing only the elements present in both sets. Use the & operator or the intersection() method.

set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

# Using & operator
print("A & B:", set_a & set_b)

# Using intersection() method
print("A.intersection(B):", set_a.intersection(set_b))

# Intersection with multiple sets
set_c = {4, 5, 8, 9}
print("A & B & C:", set_a & set_b & set_c)

# Intersection with a list
print("A & list:", set_a.intersection([3, 4, 5, 6]))

# Practical: students who passed all subjects
math_passed = {"A", "B", "C", "D", "E"}
science_passed = {"B", "D", "E", "F", "G"}
english_passed = {"A", "C", "E", "F", "H"}
passed_all = math_passed & science_passed & english_passed
print("Passed all subjects:", passed_all)

Output:

A & B: {4, 5}
A.intersection(B): {4, 5}
A & B & C: {4, 5}
A & list: {3, 4, 5}
Passed all subjects: {'E'}

Difference (-)

University Definition

The difference of two sets returns elements that are in the first set but not in the second. Order matters: A - B is not the same as B - A.

set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

# Using - operator (order matters!)
print("A - B:", set_a - set_b)   # In A but not in B
print("B - A:", set_b - set_a)   # In B but not in A

# Using difference() method
print("A.difference(B):", set_a.difference(set_b))

# Practical: finding missing items
expected = {"pen", "pencil", "eraser", "ruler", "sharpener"}
bag = {"pen", "eraser", "ruler", "notebook"}
print("Missing from bag:", expected - bag)
print("Extra in bag:", bag - expected)

# Students who failed
all_students = {"A", "B", "C", "D", "E", "F", "G", "H"}
passed = {"A", "B", "C", "D", "F"}
print("Failed:", all_students - passed)

# Chained difference
set_c = {4, 5, 6, 9, 10}
print("A - B - C:", set_a - set_b - set_c)

Output:

A - B: {1, 2, 3}
B - A: {8, 6, 7}
A.difference(B): {1, 2, 3}
Missing from bag: {'pencil', 'sharpener'}
Extra in bag: {'notebook'}
Failed: {'G', 'H', 'E'}
A - B - C: {1, 2, 3}

Symmetric Difference (^)

University Definition

The symmetric difference returns elements in either set but not in both. Equivalent to (A - B) | (B - A). Use the ^ operator or symmetric_difference() method.

set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# Using ^ operator
print("A ^ B:", set_a ^ set_b)

# Using symmetric_difference() method
print("A.symmetric_difference(B):", set_a.symmetric_difference(set_b))

# Verify equivalence
verify = (set_a - set_b) | (set_b - set_a)
print("(A-B)|(B-A):", verify)
print("Equal?", (set_a ^ set_b) == verify)

# Practical: tracking changes
before = {"feature1", "feature2", "feature3", "feature4"}
after = {"feature2", "feature3", "feature5", "feature6"}
added = after - before
removed = before - after
print("Added:", added)
print("Removed:", removed)
print("All changes:", before ^ after)

Output:

A ^ B: {1, 2, 5, 6}
A.symmetric_difference(B): {1, 2, 5, 6}
(A-B)|(B-A): {1, 2, 5, 6}
Equal? True
Added: {'feature5', 'feature6'}
Removed: {'feature1', 'feature4'}
All changes: {'feature1', 'feature4', 'feature5', 'feature6'}

Set Methods

# add() - adds a single element
colors = {"red", "blue"}
colors.add("green")
print("After add:", colors)

# add() with duplicate - no change
colors.add("red")
print("After adding duplicate:", colors)

# remove() - removes element, raises KeyError if not found
colors.remove("blue")
print("After remove:", colors)
# colors.remove("yellow")  # KeyError!

# discard() - removes element, NO error if not found
colors.discard("yellow")  # Safe! No error
print("After discard:", colors)

# pop() - removes and returns an ARBITRARY element
removed = colors.pop()
print("Popped:", removed)
print("After pop:", colors)

# clear() - removes all elements
colors.clear()
print("After clear:", colors)
print("Is empty:", len(colors) == 0)

# update() - adds elements from another iterable
s1 = {1, 2, 3}
s1.update({4, 5}, [6, 7])
print("After update:", s1)

# |= operator (same as update)
s1 |= {8, 9}
print("After |=:", s1)

Output:

After add: {'red', 'blue', 'green'}
After adding duplicate: {'red', 'blue', 'green'}
After remove: {'red', 'green'}
After discard: {'red', 'green'}
Popped: red
After pop: {'green'}
After clear: set()
Is empty: True
After update: {1, 2, 3, 4, 5, 6, 7}
After |=: {1, 2, 3, 4, 5, 6, 7, 8, 9}

University Exam Tip

remove() vs discard(): Both remove an element, but remove() raises KeyError if the element is missing, while discard() does nothing. Use discard() when you are unsure if the element exists.

Subset and Superset

University Definition

Set A is a subset of B (A <= B) if all elements of A are in B. Set A is a superset of B (A >= B) if B contains only elements of A. Two sets are disjoint if they share no common elements.

set_a = {1, 2, 3}
set_b = {1, 2, 3, 4, 5}
set_c = {6, 7, 8}

# Subset: A is subset of B if all elements of A are in B
print("{1,2,3} <= {1,2,3,4,5}:", set_a <= set_b)   # True
print("{1,2,3} <= {1,2,3,4,5}:", set_a.issubset(set_b))  # True
print("{1,2,3} <= {4,5,6}:", {1,2,3} <= {4,5,6})  # False

# Proper subset (strictly smaller)
print("{1,2,3} < {1,2,3,4,5}:", set_a < set_b)    # True
print("{1,2,3} < {1,2,3}:", {1,2,3} < {1,2,3})   # False

# Superset: A is superset of B if A contains all elements of B
print("{1,2,3,4,5} >= {1,2,3}:", set_b >= set_a)   # True
print("{1,2,3,4,5}.issuperset({1,2,3}):", set_b.issuperset(set_a))  # True

# Disjoint sets (no common elements)
print("Disjoint check:", set_a.isdisjoint(set_c))  # True
print("Disjoint check:", set_a.isdisjoint(set_b))  # False

# Practical: validating permissions
admin_perms = {"read", "write", "delete", "execute"}
user_perms = {"read", "write"}

# Check if user has all required permissions
print("User authorized:", user_perms <= admin_perms)
print("User has full access:", user_perms == admin_perms)

# Check role hierarchy
viewer_perms = {"read"}
print("Viewer <= User:", viewer_perms <= user_perms)
print("Viewer <= Admin:", viewer_perms <= admin_perms)

Output:

{1,2,3} <= {1,2,3,4,5}: True
{1,2,3} <= {1,2,3,4,5}: True
{1,2,3} <= {4,5,6}: False
{1,2,3} < {1,2,3,4,5}: True
{1,2,3} < {1,2,3}: False
{1,2,3,4,5} >= {1,2,3}: True
{1,2,3,4,5}.issuperset({1,2,3}): True
Disjoint check: True
Disjoint check: False
User authorized: True
User has full access: False
Viewer <= User: True
Viewer <= Admin: True

Operations Comparison Table

Operation Operator Method Description
Union|union()All elements from both sets
Intersection&intersection()Elements in both sets
Difference-difference()Elements in first, not in second
Sym. Difference^symmetric_difference()Elements in either but not both
Subset<=issubset()All elements of A are in B
Superset>=issuperset()A contains all elements of B
Disjoint-isdisjoint()No common elements
Add-add()Add one element
Remove-remove()Remove element (KeyError if missing)
Discard-discard()Remove element (safe)

Common Mistakes to Avoid

  • Confusing A - B with B - A — difference is not commutative.
  • Using remove() without checking membership — use discard() instead.
  • Forgetting that & requires both sides to be sets — cannot use with lists.
  • Thinking pop() removes a specific element — it removes an arbitrary one.
  • Confusing subset <= with strict subset < — equal sets are subsets but not strict subsets.

Practice Questions

  1. Given two sets of student enrollment IDs, find students enrolled in both courses, only in one course, and in either course but not both.
  2. Write a program that checks if one set is a subset of another and prints the relationship (subset, superset, disjoint, or overlapping).
  3. Implement a function that takes multiple sets and returns their intersection using a loop.
  4. Given a universal set and a student's answered questions, find the unanswered questions using set difference.

Key Points

Union (|) combines all elements from both sets.

Intersection (&) returns only common elements.

Difference (-) is not commutative: A - B != B - A.

Symmetric Difference (^) returns elements in either set but not both.

issubset() and issuperset() check containment relationships.

isdisjoint() returns True if sets have no common elements.

Use discard() over remove() to avoid KeyError.

All operations accept iterables via method versions but require sets for operators.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.