Python · Sets
Set Operations
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Introduction to Set Union
Sets can be combined using various operations. One of the most common operations is the union.
The union operation combines all elements from two or more sets. It creates a new set containing every unique element from all sets involved.
In Python, you can perform union in two ways:
- Using the
|
operator
- Using the
.union()
method
trainer_1 = {'Aquachu', 'Pyrochu'}
trainer_2 = {'Florachu', 'Rockachu'}
# Using | operator
all_codemon_1 = trainer_1 | trainer_2
print('Union with |:', all_codemon_1)
# Using .union() method
all_codemon_2 = trainer_1.union(trainer_2)
print('Union with .union():', all_codemon_2)
# Both give the same result
print('Are they equal?', all_codemon_1 == all_codemon_2)
Notice how the union contains all Codémon from both sets, with no duplicates. The order may vary since sets are unordered.
Union with Duplicates
If the same element exists in both sets, it appears only once in the union. For example, if
{'A', 'B'} | {'B', 'C'}
, the result is
{'A', 'B', 'C'}
- B appears only once even though it's in both sets.
Exercise 2 — Union with Multiple Sets
You can perform union on more than two sets at once. The result will contain all unique elements from all sets combined.
trainer_1 = {'Aquachu', 'Pyrochu'}
trainer_2 = {'Florachu', 'Rockachu'}
trainer_3 = {'Zap', 'Shadowchu'}
# Using | operator with multiple sets
all_codemon = trainer_1 | trainer_2 | trainer_3
print('All Codémon:', all_codemon)
print('Total count:', len(all_codemon))
# Using .union() method with multiple sets
all_codemon_2 = trainer_1.union(trainer_2, trainer_3)
print('\nUsing .union():', all_codemon_2)
The union operation is commutative, which means the order doesn't matter:
A | B | C
gives the same result as
C | B | A
.
Exercise 3 — Understanding Union Results
Given these two sets of Codémon:
team_a = {'Aquachu', 'Pyrochu', 'Florachu'}
team_b = {'Pyrochu', 'Zap', 'Rockachu'}
result = team_a | team_b
How many Codémon will be in the result set?
Hint : Remember that union combines all elements from both sets, but removes duplicates. Count the unique Codémon names across both sets.
Exercise 4 — Introduction to Set Intersection
The intersection operation returns only the elements that exist in ALL sets. It finds the common elements shared between sets.
In Python, you can perform intersection in two ways:
- Using the
&
operator
- Using the
.intersection()
method
trainer_a = {'Aquachu', 'Pyrochu', 'Florachu', 'Zap'}
trainer_b = {'Pyrochu', 'Zap', 'Rockachu', 'Shadowchu'}
# Using & operator
common_1 = trainer_a & trainer_b
print('Common with &:', common_1)
# Using .intersection() method
common_2 = trainer_a.intersection(trainer_b)
print('Common with .intersection():', common_2)
# Both give the same result
print('Are they equal?', common_1 == common_2)
The intersection contains only Pyrochu and Zap because they're the only Codémon that both trainers have.
Empty Intersection
If two sets have no common elements, their intersection will be an empty set
set()
. For example,
{'A', 'B'} & {'C', 'D'}
results in
set()
.
Exercise 5 — Union vs Intersection
Complete the code to find all Codémon types that exist (union) and types that are shared between both regions (intersection).
region_a_types = {'water', 'fire', 'plant', 'electric'}
region_b_types = {'fire', 'plant', 'rock', 'ice'}
# All types from both regions
all_types = region_a_types ____ region_b_types
print('All types:', all_types)
# Types found in both regions
shared_types = region_a_types ____ region_b_types
print('Shared types:', shared_types)
Options: | & - ^ + *
Hint : Think about which operator combines all elements (union) and which finds only common elements (intersection).
Exercise 6 — Introduction to Set Difference
The difference operation returns elements that are in the first set but NOT in the second set. This operation is not commutative - the order matters!
In Python, you can perform difference in two ways:
- Using the
-
operator
- Using the
.difference()
method
# Finding which Codémon are unique to each trainer
trainer_a = {'Aquachu', 'Pyrochu', 'Florachu', 'Zap'}
trainer_b = {'Pyrochu', 'Zap', 'Rockachu', 'Shadowchu'}
# Codémon only trainer A has
unique_to_a = trainer_a - trainer_b
print('Only trainer A has:', unique_to_a)
# Codémon only trainer B has
unique_to_b = trainer_b - trainer_a
print('Only trainer B has:', unique_to_b)
# Notice they are different!
print('\nAre they the same?', unique_to_a == unique_to_b)
Notice how
A - B
gives different results than
B - A
. The difference operation removes elements from the first set that also appear in the second set.
Order Matters!
Unlike union and intersection, difference is NOT commutative.
A - B
means "elements in A but not in B", while
B - A
means "elements in B but not in A". These are usually different!
Exercise 7 — Understanding Difference Order
caught = {'Aquachu', 'Pyrochu', 'Florachu'}
wanted = {'Pyrochu', 'Zap', 'Rockachu'}
result = wanted - caught
Options
• ```{'Zap', 'Rockachu'}```
• ```{'Aquachu', 'Florachu'}```
• ```{'Pyrochu'}```
• ```{'Aquachu', 'Florachu', 'Zap', 'Rockachu'}```
Hint : Remember that ```A - B``` means elements in A but not in B. Which Codémon are in wanted but not in caught?
Exercise 8 — Introduction to Symmetric Difference
The symmetric difference returns elements that are in either set, but NOT in both. It's like saying "unique to each set" or "everything except what's common".
In Python, you can perform symmetric difference in two ways:
- Using the
^
operator
- Using the
.symmetric_difference()
method
trainer_a = {'Aquachu', 'Pyrochu', 'Florachu', 'Sparkle'}
trainer_b = {'Pyrochu', 'Sparkle', 'Rockachu', 'Shadowchu'}
# Using ^ operator
unique_to_each = trainer_a ^ trainer_b
print('Unique to each:', unique_to_each)
# Using .symmetric_difference() method
unique_to_each_2 = trainer_a.symmetric_difference(trainer_b)
print('Using method:', unique_to_each_2)
# What they have in common (for comparison)
common = trainer_a & trainer_b
print('\nWhat they share:', common)
The symmetric difference contains Aquachu, Florachu (unique to A), and Rockachu, Shadowchu (unique to B). It excludes Pyrochu and Sparkle because they're in both sets.
Another Way to Think About It
Symmetric difference is equivalent to:
(A | B) - (A & B)
- it's the union minus the intersection. Or equivalently:
(A - B) | (B - A)
- elements unique to A plus elements unique to B.
Exercise 9 — Complete the Set Operations
Complete the code using the appropriate set operations to find:
1. Codémon that team A has but team B doesn't
2. Codémon that are unique to each team (not shared)
team_a = {'Aquachu', 'Pyrochu', 'Florachu'}
team_b = {'Pyrochu', 'Sparkle', 'Rockachu'}
# Codémon only in team A
only_a = team_a ____ team_b
print('Only team A:', only_a)
# Codémon unique to each team
unique_each = team_a ____ team_b
print('Unique to each:', unique_each)
Options: - ^ & | + *
Hint : Think about which operator removes elements from the first set that are in the second, and which finds elements in either but not both.
Exercise 10 — Match Set Operations with Descriptions
Match each set operation with its correct description:
Items to match
• A | B
• A & B
• A - B
• A ^ B
Definitions
• All elements from both sets
• Only elements in both sets
• Elements in A but not in B
• Elements in either set but not both
Exercise 11 — Choosing the Right Operation
You have two sets of Codémon types:
- Types that are strong against water
- Types that are strong against fire
You want to find types that are strong against water OR fire (or both). Which operation should you use?
Options
• Union (```|```)
• Intersection (```&```)
• Difference (```-```)
• Symmetric Difference (```^```)
Hint : Think about whether you want to combine all types (union), find types that satisfy both conditions (intersection), or something else.
Exercise 12 — Match Operations with Results
Given
A = {'Aquachu', 'Pyrochu', 'Florachu'}
and
B = {'Pyrochu', 'Zap'}
, match each operation with its result:
Items to match
• A | B
• A & B
• A - B
• A ^ B
Definitions
• {'Aquachu', 'Pyrochu', 'Florachu', 'Zap'}
• {'Pyrochu'}
• {'Aquachu', 'Florachu'}
• {'Aquachu', 'Florachu', 'Zap'}
Exercise 13 — Tournament Team Analysis
Two trainers are preparing for a tournament and want to analyze their teams!
1. Find which Codémon both trainers have
2. Find which Codémon are unique to each trainer (not shared by both)
3. Create a combined super team with all their Codémon
4. Add 'Shadowchu' to the super team
5. Remove 'Zap' from the super team (it's too unpredictable!)
6. Display the final super team and its size
Starter code
trainer_a = {'Aquachu', 'Pyrochu', 'Florachu'}
trainer_b = {'Pyrochu', 'Rockachu', 'Zap'}
print("=== TOURNAMENT TEAM ANALYSIS ===")
print("Trainer A:", trainer_a)
print("Trainer B:", trainer_b)
# 1. Find common Codémon
# 2. Find unique Codémon to each
# 3. Create combined super team
# 4. Add Shadowchu
# 5. Remove Zap
# 6. Display final team
print("\n=== FINAL SUPER TEAM ===")
print("Team:", super_team)
print(f"Total members: {len(super_team)}")
Back to the course