A conference compares attendees registered for two sessions.
What You Need to Understand
Set union collects items in either set, intersection selects items shared by both, and difference selects items in the first set but not the second. These operations return new sets unless you use an updating method.
When to Use It
A conference compares attendees registered for two sessions.
Step-by-Step Python Example
session_a = {"Maya", "Noa", "Avi"}
session_b = {"Noa", "Liam"}
print(sorted(session_a | session_b))
print(sorted(session_a & session_b))
print(sorted(session_a - session_b))
How the Example Works
Union includes four distinct names, intersection contains only Noa, and the first-minus-second difference contains Maya and Avi.
Example Output
['Avi', 'Liam', 'Maya', 'Noa']
['Noa']
['Avi', 'Maya']
[4]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
first_group = {1, 2, 3}
second_group = {3, 4}
print(sorted(second_group - first_group))
Important Behavior and Edge Cases
Difference is directional: A - B differs from B - A. Sets are unordered, so sort for reproducible displayed output.
Try It Yourself
Compute registrants attending B but not A.
Common Beginner Mistakes
- Difference is directional:
A - Bdiffers fromB - A. Sets are unordered, so sort for reproducible displayed output. - Depending on set iteration order or using a set when duplicates and original positions must be preserved.
Key Takeaways
- Set union collects items in either set, intersection selects items shared by both, and difference selects items in the first set but not the second.
- Union includes four distinct names, intersection contains only Noa, and the first-minus-second difference contains Maya and Avi.
- Difference is directional:
A - Bdiffers fromB - A.