Set Operations
in Python
Master union, intersection, and difference to combine, filter, and compare collections of unique elements.
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.
Why Sets Matter
The Three Core Operations
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 \).
Intersection: Find the Overlap
The intersection of sets \( A \) and \( B \) returns only elements that exist in both sets: \( A \cap B \).
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 \).
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
Example 1: Student Enrollments
Two classes share some students. Find who is in both classes and who is in either class.
Example 2: Removing Banned Words
Use set difference to filter out unwanted elements efficiently.
Example 3: Symmetric Difference
The symmetric difference \( A \triangle B \) returns elements in either set but not both: the opposite of intersection.
Chaining Multiple Operations
Set operations can be chained and used with more than two sets. This is powerful for filtering complex data.
In-Place Update Operations
Use augmented assignment operators to modify a set directly instead of creating a new one.
Common Mistakes
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?