A training session finds attendees present in two enrollment lists.
What You Need to Understand
set.intersection(*others) returns a new set of elements common to the original set and every other supplied iterable.
When to Use It
A training session finds attendees present in two enrollment lists.
Step-by-Step Python Example
group_a = {"Maya", "Noa", "Liam"}
group_b = {"Noa", "Avi"}
print(sorted(group_a.intersection(group_b)))
How the Example Works
Only Noa occurs in both groups. The originals remain unchanged.
Example Output
['Noa']
{3}
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
print({1, 2, 3}.intersection({2, 3}, {3, 4}))
Important Behavior and Edge Cases
Do not confuse intersection with union. Intersections of multiple sets become no larger as additional requirements are added.
Try It Yourself
Find IDs shared by three groups.
Common Beginner Mistakes
- Do not confuse intersection with union. Intersections of multiple sets become no larger as additional requirements are added.
- Using the wrong collection method for this operation without checking whether it mutates the object, returns a result, or raises on missing data.
Key Takeaways
set.intersection(*others)returns a new set of elements common to the original set and every other supplied iterable.- Only Noa occurs in both groups.
- Do not confuse intersection with union.