Python Master Course V2 — 046. Set Operations
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 05 · LESSON 046/200
Set Operations
Estimated study: 75–100 minutes · Prerequisite: Lesson 045 and earlier collections lessons.
Video lesson
Video not yet available. A dedicated space is reserved for a verified video URL or player.
Learning outcomes
- Explain the behavior and use cases of set operations.
- Apply the correct Python syntax and predict output.
- Handle missing, duplicate and invalid data deliberately.
- Implement a practical real-world processing project.
- Write edge-case tests and explain failures.
Detailed explanation
Union combines unique members, intersection finds shared members, difference finds one-sided members, and symmetric difference finds members on exactly one side.
Begin by defining the expected data types, key constraints, and the output contract. Consider whether the operation creates a new collection or mutates an existing one. For reports, sort results where stable ordering matters. When records represent business data, missing information should be reported rather than silently replaced unless a clear rule permits defaults.
Professional Python code benefits from small functions, descriptive names, explicit validation and repeatable tests. Assess the complexity of nested operations when data volumes grow.
Understand Set Operations
Translate a comparison question into an operation
Set operations compare membership across collections. Union, written a | b, includes every value on either side. Intersection, a & b, includes only shared members. Difference, a - b, includes members of a absent from b. Symmetric difference, a ^ b, includes values appearing on exactly one side. Draw two overlapping circles if the symbols feel abstract: each operation selects a different region.
expected = {"A", "B", "C"}
actual = {"B", "C", "D"}
print("all:", sorted(expected | actual))
print("matched:", sorted(expected & actual))
print("missing:", sorted(expected - actual))
print("unexpected:", sorted(actual - expected))
print("different:", sorted(expected ^ actual))
all: ['A', 'B', 'C', 'D']
matched: ['B', 'C']
missing: ['A']
unexpected: ['D']
different: ['A', 'D']
Follow the names rather than memorizing subtraction blindly. Expected minus actual finds missing deliveries. Reversing the operands finds unexpected deliveries. Union, intersection and symmetric difference give the same membership when the operands are reversed; difference generally does not. These operators return new sets, leaving both inputs unchanged. Methods such as difference_update intentionally change the receiving set and should be used only when the original membership is no longer needed.
Ask containment questions with comparisons
required <= available asks whether every required member is available; equality is allowed. A strict subset uses < and additionally requires the available set to have at least one extra member. Reverse the comparison for a superset. a.isdisjoint(b) returns True when the sets share no member. These operations produce booleans rather than collections, so they fit conditions such as prerequisite checks.
required = {"read"}
available = {"read", "write"}
print(required <= available)
print(required < required)
print(required.isdisjoint({"delete"}))
print(set() <= required)
True
False
True
True
The empty set is a subset of every set because it imposes no missing membership requirement. It is also disjoint from every set. These facts give useful boundary behavior: no required permissions is satisfied, and no expected deliveries produces no missing IDs. Decide whether an empty requirement is valid in the application; the mathematical result cannot decide the business policy for you.
Reconcile identifiers, then inspect their records
For the project, convert each source to a set once, calculate missing, unexpected and matched groups, and sort each group for a repeatable report. Use missing and unexpected separately rather than just symmetric difference when the direction affects the next action. Matched IDs only establish presence on both sides. They do not prove that quantities, names or other fields match; use dictionary lookups to compare those fields afterward.
Converting a list to a set discards duplicate counts before comparison. An actual delivery list containing A twice and B once has the same ID membership as a list containing A and B once each. If duplicates signal accidental repeated processing, report them before deduplication or compare frequency dictionaries. A professional reconciliation states exactly what “matched” means: same identifier set, same occurrence counts, or same complete records.
Runnable example
Setup: Python 3.10+, standard library only. Save the following as lesson_046.py and run python lesson_046.py. The output is expected, not a claim of execution on Smartyfy.
expected={"A","B","C"}
actual={"B","C","D"}
print(sorted(expected&actual))
print(sorted(expected-actual))
print(sorted(actual-expected))
Expected output:
['B', 'C'] ['A'] ['D']
Walkthrough: Identify the starting collection, trace each operation and compare the final state with the expected output. Change one input to verify your understanding.
Real-world project — Set Operations in practice
Build a reusable Python function for a realistic record-processing workflow. Keep the calculation separate from user interaction and make output deterministic. This project reconciles identifier membership only: matched IDs do not prove equal quantities, duplicate counts, or complete records.
def reconcile_ids(expected,actual):
e,a=set(expected),set(actual)
return {"missing":sorted(e-a),"unexpected":sorted(a-e),"matched":sorted(e&a)}
print(reconcile_ids(["A","B","C"],["B","C","D"]))
Expected output:
{'missing': ['A'], 'unexpected': ['D'], 'matched': ['B', 'C']}
Extra project: Add validation for malformed records, a CSV export, summary totals, and five independent tests. Cover empty data, duplicates, one-sided missing records and large inputs where applicable. Explain how your algorithm’s running time grows with the input size.
Common mistakes and best practices
- Assuming all required keys and values exist.
- Confusing ordered and unordered collections.
- Overwriting duplicate dictionary keys without realizing it.
- Accidentally mutating shared nested data.
- Ignoring edge cases or using unsafe defaults for missing business records.
Practice and explained answers
Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.
Optional hint for question 1
Start with the expected set and remove identifiers found on the actual side.
1. Which expression finds expected IDs that never arrived?
Answer and reasoning:
expected - actual. The left operand defines candidates and the right operand removes those found there. actual - expected answers the opposite question.
2. Compute the symmetric difference of {1, 2} and {2, 3}.
Answer and reasoning:
The members are 1 and 3; sorted output is [1, 3]. The shared member 2 is excluded because it appears on both sides.
3. Are {"read"} <= {"read"} and {"read"} < {"read"} both true?
Answer and reasoning:
No. The first is True because every member is included. The second is False because a strict subset cannot be equal to the other set.
4. Does matched = expected & actual mutate expected?
Answer and reasoning:
No. It creates a new set assigned to matched. expected.intersection_update(actual) would instead mutate expected and return None.
5. Why can equal ID sets still conceal an inventory error?
Answer and reasoning:
Sets ignore counts and record fields. Expected ["A", "A", "B"] and actual ["A", "B"] have equal sets but different A counts. Compare a frequency mapping or keyed quantities when quantities matter.
Mastery checkpoint
Explain set operations, predict the code output, run the project and create three new tests, including a failure case.
Summary: Union combines unique members, intersection finds shared members, difference finds one-sided members, and symmetric difference finds members on exactly one side.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.