Compare Groups with Python Set Operations
Compare two groups with union, intersection, and difference while returning deterministic sorted results.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Compare Groups with Python Set Operations
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
Here are two lists of group members. Ada appears twice on the left because of a duplicated record. We want one clear comparison: names in both groups, only the left group, and only the right group. Pause before the first run and predict whether a list comprehension will count Ada once or twice. Our answer should represent unique members, not check-in events. This distinction determines whether a set is appropriate. If the product wanted attendance counts, we would choose a different data structure and a different lesson. A set is more than a quick way to remove duplicates. Union combines values from either side, intersection keeps values shared by both
- 00:41
sides, and difference keeps values in one side but not the other. These operations answer concrete questions about membership: who is in both groups, who joined only one group, and who is in at least one group. When output order matters, sort the resulting sets before returning or printing them. Sets themselves do not promise a display order that should appear in a report. The broken result contains Ada twice. It passes a quick happy-path check when every name appears once, but duplicates expose the mismatch between list iteration and unique membership. Testing whether each left name appears in the right list also repeats searches.
- 01:22
We will convert both lists to sets once. That conversion discards multiplicity intentionally. The output can then be described with three familiar regions of a Venn diagram. We do not need to draw a diagram to implement them, but it helps to verbalize each region before writing operators. The broken helper walks the first input list and adds an item every time it also appears in the second list. A repeated item in the first list appears twice in the output, even though common members should be a set. Membership testing against a list can also take repeated linear scans. Convert both inputs to sets once, then use set operators.
- 02:04
The conversion deliberately removes duplicates because our contract compares members, not attendance events or counts. The intersection returns the shared Ada member. Left minus right returns Lin, while right minus left returns Grace. Those last two expressions are not interchangeable. The set operators produce sets whose print order should not be used as a stable report order. We wrap each with sorted so the browser output and checks are deterministic. Try swapping the two input groups and predict which keys in the result change. The common region stays the same; the exclusive regions trade places.
- 02:44
That is a useful property to test. Use left_set & right_set for common items, left_set - right_set for only-left, right_set - left_set for only-right, and left_set | right_set for all distinct items. The order of subtraction matters: swapping operands changes which side is exclusive. Return sorted lists so a printed result and automated test are stable. This example uses comparable strings; mixed incomparable types would need an explicit ordering key or a different output contract. The corrected helper constructs sets from the caller's lists without mutating either list. It computes the three required regions and returns a dictionary whose keys name them.
- 03:28
The task does not ask for a union in the returned report, but the lesson shows union as a consistency check: every distinct member must occur in exactly one of the three regions, and the total size of their union should match. If mixed types cannot be ordered together, sorted will raise; our contract uses comparable names, so that is outside this example. The function returns sorted lists rather than raw sets because this website displays and tests the result. Sorting is a presentation decision layered on top of set mathematics. The set conversion is a semantic decision: it says membership is binary.
- 04:08
For a large dataset, building two sets takes memory proportional to distinct members, but repeated membership checks become efficient. In a tiny exercise, clarity matters more than microbenchmarking. Name the inputs left and right consistently, and always test a case where the difference directions produce different values. Consider a classroom roster comparison: left is the people enrolled on Monday and right is the people enrolled on Friday. The common names stayed enrolled, left only names departed, and right only names joined. That story makes the direction of subtraction memorable. Check another edge case where both lists are empty: all three result lists should
- 04:50
be empty. When only one side is empty, all distinct names belong to one exclusive region. Repeated names inside one input still appear once because the task asks about membership. If your real application needs repeated transactions or visit counts, keep those counts separately instead of trying to reconstruct them after converting to a set. The final run tests an empty left side and disjoint groups. Both are common edge cases: there may be no members in one cohort, and two cohorts may share no one. A helper that assumes one shared value would fail here.
- 05:30
The practical task also checks that duplicate input names do not duplicate output names and that inputs remain unchanged. Take the quiz to reinforce intersection, directional difference, and why sorting is necessary for stable display. Then explain a case where a set would be wrong because repeated events actually matter. Test duplicates, empty sides, fully disjoint groups, and equal groups. Avoid mutating caller input; the operators here construct new sets. Also state when not to use a set: if duplicates carry meaning, such as repeated purchases, conversion loses information. The practical task returns common, left- only, and right-only members as sorted
- 06:12
lists. The quiz checks both the mathematics and the Python behavior. This extends the introductory tuple-and- set lesson without repeating its deduplication exercise.
Understand the concept
A set is more than a quick way to remove duplicates. Union combines values from either side, intersection keeps values shared by both sides, and difference keeps values in one side but not the other. These operations answer concrete questions about membership: who is in both groups, who joined only one group, and who is in at least one group. When output order matters, sort the resulting sets before returning or printing them. Sets themselves do not promise a display order that should appear in a report.
The broken helper walks the first input list and adds an item every time it also appears in the second list. A repeated item in the first list appears twice in the output, even though common members should be a set. Membership testing against a list can also take repeated linear scans. Convert both inputs to sets once, then use set operators. The conversion deliberately removes duplicates because our contract compares members, not attendance events or counts.
Use left_set & right_set for common items, left_set - right_set for only-left, right_set - left_set for only-right, and left_set | right_set for all distinct items. The order of subtraction matters: swapping operands changes which side is exclusive. Return sorted lists so a printed result and automated test are stable. This example uses comparable strings; mixed incomparable types would need an explicit ordering key or a different output contract.
Test duplicates, empty sides, fully disjoint groups, and equal groups. Avoid mutating caller input; the operators here construct new sets. Also state when not to use a set: if duplicates carry meaning, such as repeated purchases, conversion loses information. The practical task returns common, left-only, and right-only members as sorted lists. The quiz checks both the mathematics and the Python behavior. This extends the introductory tuple-and-set lesson without repeating its deduplication exercise.
- Intersection finds common members
- Difference is directional
- Union keeps members from either side
- Sort before display when deterministic order matters
See it step by step
Read the code, predict the output, then compare it with the result.
01. Find common members
a = {'Ada', 'Lin'}
b = {'Ada', 'Grace'}
print(sorted(a & b))
['Ada']Intersection returns the shared Ada member.
02. Compare directional differences
a = {'Ada', 'Lin'}
b = {'Ada', 'Grace'}
print(sorted(a - b))
print(sorted(b - a))
['Lin']
['Grace']Subtracting in opposite directions answers two different questions.
03. Form a complete union
a = {'Ada', 'Lin'}
b = {'Ada', 'Grace'}
print(sorted(a | b))
['Ada', 'Grace', 'Lin']Union contains every distinct member from either group.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Find the overlap
A set is more than a quick way to remove duplicates. Union combines values from either side, intersection keeps values shared by both sides, and difference keeps values in one side but not the other. These operations answer concrete questions about membership: who is in both groups, who joined only one group, and who is in at least one group. When output order matters, sort the resulting sets before returning or printing them. Sets themselves do not promise a display order that should appear in a report.
The intersection is a set even if the original lists contained repeated names. Add a second Ada to the left list and predict why the result still has one. Decide whether your product counts membership or events before converting.
a = {'Ada', 'Lin'}
b = {'Ada', 'Grace'}
print(sorted(a & b))
['Ada']- Convert both inputs to sets.
- Use & to find shared members.
Keep left and right differences separate
The broken helper walks the first input list and adds an item every time it also appears in the second list. A repeated item in the first list appears twice in the output, even though common members should be a set. Membership testing against a list can also take repeated linear scans. Convert both inputs to sets once, then use set operators. The conversion deliberately removes duplicates because our contract compares members, not attendance events or counts.
Directional difference is a common source of reversed labels. Read a minus b aloud as members in a that are not in b. In the browser task, left_only and right_only must never be swapped.
a = {'Ada', 'Lin'}
b = {'Ada', 'Grace'}
print(sorted(a - b))
print(sorted(b - a))
['Lin']
['Grace']- Compute a - b and b - a separately.
- Sort each result for stable output.
Combine for a complete inventory
Use left_set & right_set for common items, left_set - right_set for only-left, right_set - left_set for only-right, and left_set | right_set for all distinct items. The order of subtraction matters: swapping operands changes which side is exclusive. Return sorted lists so a printed result and automated test are stable. This example uses comparable strings; mixed incomparable types would need an explicit ordering key or a different output contract.
Union helps check the total distinct population. The union count equals common plus left-only plus right-only counts. Use that relation as an additional sanity check when building a report.
a = {'Ada', 'Lin'}
b = {'Ada', 'Grace'}
print(sorted(a | b))
['Ada', 'Grace', 'Lin']- Compute a | b for the full group.
- Compare its size with the three regions.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Convert each input to a set. Compute sorted(a & b), sorted(a - b), and sorted(b - a) for the three keys.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Counting repeated members twice
[name for name in left if name in right]sorted(set(left) & set(right))What happens: A repeated left-side name appears twice in common.
The comparison is about unique membership, not event counts.
Reversing set difference
right_set - left_set # left-onlyleft_set - right_set # left-onlyWhat happens: The function returns people only on the right.
Difference keeps values from the first operand that are absent from the second.