SECTION 1
Historical Context & Motivation
Before computers ever existed, mathematicians needed a way to reason about groups of objects. In the 1870s, German mathematician Georg Cantor formalized the idea of a set — an unordered collection of distinct elements. His work became the foundation of modern mathematics and, eventually, the data structures you use in programming today.
Fast forward to the age of computing, and sets turned out to be incredibly useful for tasks like removing duplicates from data, checking membership quickly, and combining or comparing groups of items. Python introduced a built-in set type to give programmers direct access to these powerful mathematical operations.
1874 • Cantor Founds Set Theory
1880s • Venn Diagrams Emerge
1960s • Sets Enter Programming
2004 • Python Adds Built-in Sets
The core question that set operations answer is simple but powerful: given two or more groups of items, how can you efficiently combine them, find what they share, or figure out what's unique to each group? Python's set type makes these tasks surprisingly straightforward.
SECTION 2
Core Principles & Definitions
Before diving into operations, you need to understand what makes a Python set special. A set is an unordered collection where every element appears exactly once. You create one with curly braces or the set() constructor. Once you have two or more sets, three fundamental operations let you combine and compare them.
Union ( | )
Intersection ( & )
Difference ( - )
No Duplicates
KEY TAKEAWAY
SECTION 3
Visual Explanation — Venn Diagrams for Set Operations
The best way to understand set operations is to see them. The diagram below shows two sets, A and B, as overlapping circles. Each operation highlights a different region of the diagram.
In the concrete example, union gives {1, 2, 3, 4, 5, 6} — every element from both sets. Intersection gives {3, 4} — only the shared elements. Difference A − B gives {1, 2} — what A has that B doesn't. Notice that B − A would give {5, 6} instead, since difference depends on order.
SECTION 4
Python Syntax — Operators and Methods
Python gives you two ways to perform each set operation: a symbolic operator and a named method. Both produce the same result, so choose whichever makes your code clearer. The operator versions are shorter, while the method versions accept any iterable (like a list), not just sets.
UNION
Returns a new set containing every element found in A, in B, or in both. Neither A nor B is modified.
INTERSECTION
Returns a new set containing only elements present in both A and B. Elements unique to either set are excluded.
DIFFERENCE
Returns a new set containing elements that are in A but not in B. The order matters — A − B ≠ B − A in general.
SYMMETRIC DIFFERENCE (BONUS)
Returns elements in A or B, but not in both. This is the union minus the intersection — everything that's unique to one set or the other.
Operator vs. Method
| operator requires both sides to be sets. The .union() method can accept a list, tuple, or any iterable as its argument — Python converts it to a set internally. For example, {1, 2}.union([2, 3]) works, but {1, 2} | [2, 3] raises a TypeError.SECTION 5
Detailed Breakdown — Common Code Patterns
Let's look at how these operations appear in real Python code. Each example creates two sets and applies all three core operations. The diagram below maps Python code to the results it produces.
| Operation | Operator | Method | Returns |
|---|---|---|---|
| Union | A | B | A.union(B) | All elements from A and B |
| Intersection | A & B | A.intersection(B) | Elements in both A and B |
| Difference | A - B | A.difference(B) | Elements in A but not in B |
| Symmetric Diff. | A ^ B | A.symmetric_difference(B) | Elements in A or B, not both |
Quick reference: all four set operations with their operator and method syntax.
SECTION 6
Worked Example — Playlist Merging
Imagine you and a friend each have a music playlist stored as a Python set. You want to find all unique songs across both playlists, the songs you both like, and the songs only you have. Let's walk through this step by step.
Merging Two Music Playlists
- 1
Step 1 — Define the sets
Create two sets representing each playlist. Note that sets use curly braces and hold unique string values.my_songs = {"Blinding Lights", "Levitating", "Watermelon Sugar", "Peaches"}friend_songs = {"Levitating", "Peaches", "Stay", "Good 4 U"}Two sets created: my_songs has 4 elements, friend_songs has 4 elements. - 2
Step 2 — Find all unique songs (Union)
Use the|operator to combine both playlists. Duplicates are automatically removed.all_songs = my_songs | friend_songs{"Blinding Lights", "Levitating", "Watermelon Sugar", "Peaches", "Stay", "Good 4 U"}— 6 unique songs total. - 3
Step 3 — Find shared favorites (Intersection)
Use the&operator to find songs that appear in both playlists.shared = my_songs & friend_songs{"Levitating", "Peaches"}— the 2 songs you both enjoy. - 4
Step 4 — Find songs only you have (Difference)
Use the-operator. Since we writemy_songs - friend_songs, we get elements in my_songs that are NOT in friend_songs.only_mine = my_songs - friend_songs{"Blinding Lights", "Watermelon Sugar"}— songs only on your playlist. - 5
Step 5 — Verify with len()
A useful check: the size of the union should equal the size of A plus the size of B minus the size of the intersection (to avoid double-counting). We havelen(all_songs)= 6, and 4 + 4 − 2 = 6. ✓ The math confirms our results are correct.|A ∪ B| = |A| + |B| − |A ∩ B| → 6 = 4 + 4 − 2 ✓
SECTION 7
Sets vs. Lists vs. Dictionaries
Python offers several collection types, and choosing the right one matters. Sets are the best tool when you care about uniqueness and membership testing, but they have trade-offs compared to lists and dictionaries. The table below highlights the key differences.
| Feature | Set | List | Dictionary |
|---|---|---|---|
| Duplicates allowed? | No | Yes | No (keys) |
| Ordered? | No | Yes | Insertion order (3.7+) |
| Membership check speed | O(1) average | O(n) | O(1) average |
| Built-in set operations? | Yes | No | No |
| Index access (e.g., [0])? | No | Yes | By key |
Comparison of Python's three main collection types.
WHEN TO USE A SET
SECTION 8
Connection to Advanced Concepts
The set operations you've learned here are just the beginning. As you advance in computer science, you'll encounter these same ideas in increasingly powerful contexts. Database queries use set-like operations (SQL's UNION, INTERSECT, and EXCEPT), and understanding sets will help you write efficient algorithms for searching and filtering data.
| Introductory Concept | Advanced Extension |
|---|---|
| Basic set operations (|, &, -) | frozenset — an immutable set you can use as a dictionary key or put inside another set |
| Creating sets manually | Set comprehensions — e.g., {x**2 for x in range(10)} builds sets dynamically |
| Comparing two sets | Subset/superset checks — A.issubset(B) and A.issuperset(B) test containment |
| Set difference for filtering | Database EXCEPT/MINUS operations and relational algebra in SQL |
| Membership check (in) | Hash tables — the data structure underlying sets, enabling O(1) lookups |
How today's concepts connect to more advanced topics.
Once you're comfortable with the basics, try chaining operations together. For example, (A | B) - (A & B) is equivalent to the symmetric difference A ^ B. Discovering these relationships deepens your understanding of how set operations relate to each other and to Boolean logic.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
Show answer
Question 2: BASIC CALCULATION
x = {10, 20, 30, 40} and y = {30, 40, 50, 60}, determine the result of each: (a) x | y, (b) x & y, (c) x - y.Show answer
x | y = {10, 20, 30, 40, 50, 60} — all elements from both sets combined, with duplicates removed. (b) x & y = {30, 40} — only 30 and 40 appear in both sets. (c) x - y = {10, 20} — 10 and 20 are in x but not in y. The shared elements (30 and 40) are removed by the difference operation.Question 3: INTERMEDIATE
a = {1, 2, 3, 4, 5}, b = {4, 5, 6, 7}, and c = {5, 6, 7, 8, 9}. Write a Python expression to find elements that are in all three sets. Then write another expression to find elements that are in at least one of the three sets.Show answer
a & b & c which yields {5}, since 5 is the only element present in a, b, and c. To find elements in at least one set (union of all three): a | b | c which yields {1, 2, 3, 4, 5, 6, 7, 8, 9}. Python allows chaining set operators, and they evaluate left to right. You can also write these using the method syntax: a.intersection(b, c) and a.union(b, c) — notice the methods can accept multiple arguments.Question 4: APPLIED
math_pass = {"Ana", "Ben", "Cara", "Dan", "Eve"} and sci_pass = {"Ben", "Cara", "Fay", "Gus"}. Write Python code to find: (a) students who passed both exams, (b) students who passed math but not science, and (c) the total number of students who passed at least one exam.Show answer
both = math_pass & sci_pass → {"Ben", "Cara"}. These two students passed both exams. (b) math_only = math_pass - sci_pass → {"Ana", "Dan", "Eve"}. These three passed math but not science. (c) len(math_pass | sci_pass) → 7. The union contains Ana, Ben, Cara, Dan, Eve, Fay, and Gus. Using len() on the union gives the count. You can verify: 5 + 4 − 2 = 7, matching the formula |A ∪ B| = |A| + |B| − |A ∩ B|.Question 5: CRITICAL THINKING
(A - B) | (B - A) always produces the same result as A ^ B (symmetric difference). Is this claim correct? Prove your reasoning by testing with A = {1, 2, 3} and B = {2, 3, 4}, and then explain why the relationship holds (or doesn't) for any two sets.Show answer
SUMMARY
Lesson Summary
Summary
Python sets are unordered collections of unique elements that support three core operations: union (|) combines all elements from both sets, intersection (&) keeps only shared elements, and difference (-) returns elements in the first set but not the second. Each operation has both an operator and a method form, and none of them modify the original sets.
Sets excel at fast membership testing (O(1) on average) and automatic deduplication. Remember that difference is order-dependent (A − B ≠ B − A), while union and intersection are not. The bonus symmetric difference (^) gives elements in exactly one set. These operations form the foundation for database queries, data cleaning, and algorithmic problem-solving you'll encounter in more advanced courses.