01 / 20

Set Operations
in Python

Master union, intersection, and difference to combine, filter, and compare collections of unique elements.

Python

What Is a Set?

A set is an unordered collection of unique elements. Unlike lists, sets cannot contain duplicates, and the elements have no guaranteed order.

# Creating sets in Python fruits = {"apple", "banana", "cherry"} numbers = set([1, 2, 3, 2, 1]) print(numbers) # {1, 2, 3} - duplicates removed

Why Sets Matter

★ Fast Lookups
Checking if an element exists is \( O(1) \) on average: much faster than a list.
★ No Duplicates
Sets automatically eliminate repeated values, perfect for deduplication tasks.
★ Math Operations
Union, intersection, and difference mirror mathematical set theory directly.

The Three Core Operations

Union A | B All elements Intersection A & B Shared elements Difference A - B Only in A A B A B A B Python syntax: methods or operators A.union(B) or A | B · A.intersection(B) or A & B · A.difference(B) or A - B

Union: Combine Everything

The union of sets \( A \) and \( B \) produces a new set containing every element from both sets, with duplicates removed: \( A \cup B \).

A = {1, 2, 3} B = {3, 4, 5} # Two equivalent ways print(A | B) # {1, 2, 3, 4, 5} print(A.union(B)) # {1, 2, 3, 4, 5}

Intersection: Find the Overlap

The intersection of sets \( A \) and \( B \) returns only elements that exist in both sets: \( A \cap B \).

A = {1, 2, 3, 4} B = {3, 4, 5, 6} # Two equivalent ways print(A & B) # {3, 4} print(A.intersection(B)) # {3, 4}

Difference: What's Left Over

The difference \( A - B \) returns elements in \( A \) that are not in \( B \). Order matters: \( A - B \neq B - A \).

A = {1, 2, 3, 4} B = {3, 4, 5, 6} print(A - B) # {1, 2} print(B - A) # {5, 6} print(A.difference(B)) # {1, 2}

Methods vs Operators

Operation Operator Method
Union A | B A.union(B)
Intersection A & B A.intersection(B)
Difference A - B A.difference(B)
Sym. Difference A ^ B A.symmetric_difference(B)

How to Apply Set Operations

1
Identify your data. What two collections are you comparing? Convert them to sets if needed.
2
Choose the operation. Do you want everything (union), overlap (intersection), or what's unique (difference)?
3
Pick method or operator. Use | , & , - for concise code, or .union(), .intersection(), .difference() for readability.
4
Check the result. Remember: the result is a new set. The originals remain unchanged.

Example 1: Student Enrollments

Two classes share some students. Find who is in both classes and who is in either class.

math_class = {"Alice", "Bob", "Carol", "Dave"} science_class = {"Bob", "Dave", "Eve", "Frank"} # Students in BOTH classes both = math_class & science_class print(both) # {"Bob", "Dave"} # ALL unique students all_students = math_class | science_class print(all_students) # {"Alice", "Bob", "Carol", "Dave", "Eve", "Frank"}

Example 2: Removing Banned Words

Use set difference to filter out unwanted elements efficiently.

words = {"hello", "spam", "world", "junk", "python"} banned = {"spam", "junk", "trash"} clean = words - banned print(clean) # {"hello", "world", "python"}

Example 3: Symmetric Difference

The symmetric difference \( A \triangle B \) returns elements in either set but not both: the opposite of intersection.

A = {1, 2, 3, 4} B = {3, 4, 5, 6} print(A ^ B) # {1, 2, 5, 6} # Equivalent to: (A | B) - (A & B) print((A | B) - (A & B)) # {1, 2, 5, 6}
1, 2 3, 4 5, 6 A B Highlighted: A ^ B (symmetric difference)

Chaining Multiple Operations

Set operations can be chained and used with more than two sets. This is powerful for filtering complex data.

freshmen = {"Alice", "Bob", "Carol"} honors = {"Bob", "Dave", "Eve"} athletes = {"Carol", "Eve", "Frank"} # Freshmen who are also in honors print(freshmen & honors) # {"Bob"} # Anyone in any group print(freshmen | honors | athletes) # {"Alice", "Bob", "Carol", "Dave", "Eve", "Frank"} # Freshmen who are NOT athletes print(freshmen - athletes) # {"Alice", "Bob"}

In-Place Update Operations

Use augmented assignment operators to modify a set directly instead of creating a new one.

A = {1, 2, 3} B = {3, 4, 5} A |= B # A is now {1, 2, 3, 4, 5} # Same as A.update(B) C = {1, 2, 3} C &= B # C is now {3} # Same as C.intersection_update(B) D = {1, 2, 3} D -= B # D is now {1, 2} # Same as D.difference_update(B)

Common Mistakes

✕ Empty Set with {}
Writing x = {} creates an empty dict, not a set. Use x = set() for an empty set.
✕ Confusing - and ^
A - B removes B's elements from A. A ^ B keeps elements in either but not both. They are different operations.
✕ Order Assumption
Sets are unordered. Printing may show different orders each time. Never rely on index positions.

Quick Reference Table

Operation Syntax Result Returns
Union A | B All elements New set
Intersection A & B Shared elements New set
Difference A - B In A not B New set
Sym. Diff. A ^ B In either, not both New set
Update A |= B Add B into A Mutates A

Question 1 of 5

Given A = {1, 2, 3} and B = {2, 3, 4}, what is the result of A | B?

Question 2 of 5

Given X = {10, 20, 30, 40} and Y = {30, 40, 50}, what does X & Y return?

Question 3 of 5

What does x = {} create in Python?

Question 4 of 5

Given A = {"a", "b", "c"} and B = {"b", "c", "d"}, what is A - B?

Question 5 of 5

Which line of code will modify set A in place to include all elements from B?