Set Union and Intersection in Python
Core idea
For sets a and b, a | b or a.union(b) produces all members from either group. a & b or a.intersection(b) selects members present in both. These operations produce new sets rather than modifying the operands.
morning = {2, 4, 8}afternoon = {4, 9}print(sorted(morning | afternoon))Participant 4 appears only once in the union.
Find shared registrations
morning = {2, 4, 8}afternoon = {4, 9}print(sorted(morning & afternoon))print(sorted(morning))Only 4 appears in both; morning is unchanged.
Use a list as a method argument
stock = {"pen", "pad"}print(sorted(stock.union(["pad", "clip"])))print(sorted(stock.intersection(["pad", "clip"])))The method forms accept lists as sources of members.
Common mistake
With built-in sets and lists, a | some_list raises TypeError. Use a.union(some_list) or convert the list to a set first.
Practice
Compare two lists of workshop registrations. Print the sorted union and intersection, including a case where the groups share no members.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Union and intersection
Check your understanding of union and intersection.
What is printed?
print(sorted({1, 2} | {2, 3}))What is printed?
print(sorted({1, 2} & {2, 3}))What is printed?
a = {1}b = a.union([2])print(sorted(a))Which accepts a list of members as the second source?