Python · Sets
Adding Removing Elements
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Adding Elements with add()
Sets can be modified, we can add, remove, or update elements. Let's start easy with the
add()
method.
The
add()
method allows you to add a single element to a set. Remember that sets automatically maintain uniqueness, so adding an element that already exists won't create a duplicate.
Basic syntax:
my_set.add(element)
codemon_types = {'water', 'fire', 'plant'} print("Original set:", codemon_types) # Add a new type codemon_types.add('electric') print("After adding 'electric':", codemon_types) # Try adding a duplicate codemon_types.add('water') print("After trying to add 'water' again:", codemon_types)
Notice how adding 'water' again didn't create a duplicate. The set still contains only unique elements.
add() vs append()
Unlike lists which use
append()
, sets use
add()
to add elements. This is because sets don't have a concept of order or position where elements are 'appended' to.
Exercise 2 — Understanding add() with Duplicates
What will be the output of the following code?
codemon_names = {'Aquachu', 'Pyrochu'} codemon_names.add('Aquachu') codemon_names.add('Florachu') print(len(codemon_names))
Options
• ```3```
• ```4```
• ```2```
• An error will occur
Hint : Remember that sets automatically prevent duplicates. Count how many unique elements will be in the set after all operations.
Exercise 3 — Adding Multiple Elements with update()
While
add()
adds a single element,
update()
allows you to add multiple elements at once from any iterable (list, tuple, another set, etc.).
Basic syntax:
my_set.update(iterable)
my_codemon = {'Aquachu', 'Pyrochu'} print("Original set:", my_codemon) # Add multiple Codémon from a list new_codemon = ['Florachu', 'Zap'] my_codemon.update(new_codemon) print("After update with list:", my_codemon)
Notice how
update()
can accept lists, sets, or any iterable. It automatically handles duplicates, just like
add()
.
Common Mistake
Don't confuse
add()
and
update()
! If you try
my_set.add(['a', 'b'])
, Python will try to add the entire list as a single element (which will cause an error because lists aren't hashable). Use
update()
for multiple elements!
Exercise 4 — Using add() and update() Correctly
Complete the code to add elements to the set correctly. Use
add()
for single elements and
update()
for multiple elements.
# Create a set of caught Codémon caught_codemon = {'Aquachu'} caught_codemon.____('Pyrochu') new_catches = ['Florachu', 'Zap', 'Rockachu'] caught_codemon.____(new_catches) print(caught_codemon)
Options: add update append extend insert add update
Hint : Think about which method is used for single elements versus multiple elements. One adds a single item, the other adds from an iterable.
Exercise 5 — Removing Elements: remove() vs discard()
Python provides two methods to remove specific elements from a set:
remove()
and
discard()
. The key difference is how they handle elements that don't exist in the set.
remove(): - Removes the specified element - Raises a
KeyError
if the element doesn't exist - Use when you're certain the element exists
discard(): - Removes the specified element - Does nothing if the element doesn't exist (no error) - Use when you're unsure if the element exists
codemon_team = {'Aquachu', 'Pyrochu', 'Florachu'} print("Original team:", codemon_team) # Using discard() - safe even if element doesn't exist codemon_team.discard('Pyrochu') print("After discard('Pyrochu'):", codemon_team) codemon_team.discard('Zap') # Doesn't exist, but no error! print("After discard('Zap'):", codemon_team)
codemon_team = {'Aquachu', 'Pyrochu', 'Florachu'} print("Original team:", codemon_team) # Using remove() - will work if element exists codemon_team.remove('Aquachu') print("After remove('Aquachu'):", codemon_team) # Uncommenting the next line would cause a KeyError # codemon_team.remove('Zap') # KeyError!
Exercise 6 — Choosing Between remove() and discard()
You're writing code to manage a player's Codémon inventory. The player can release Codémon they no longer want, but sometimes they might try to release a Codémon they don't have. Which method should you use?
Options
• ```discard()```
• ```remove()```
• ```pop()```
• ```clear()```
Hint : Think about whether you want the program to crash with an error or continue running smoothly even if the player makes a mistake.
Exercise 7 — Implementing remove() and discard()
Complete the code to manage a Codémon collection.
active_codemon = {'Aquachu', 'Pyrochu', 'Florachu'} # Aquachu is in for sure active_codemon.____('Aquachu') # We're not sure if Zap is in the set active_codemon.____('Zap') print(active_codemon)
Options: remove discard pop delete remove discard
Hint : Consider which method raises an error if the element doesn't exist and which one doesn't.
Exercise 8 — pop() and clear() Methods
Two more useful methods for removing elements from sets are
pop()
and
clear()
.
pop(): - Removes and returns an arbitrary element from the set - Raises a
KeyError
if the set is empty - You don't control which element gets removed - Useful when you need any element from the set
clear(): - Removes all elements from the set - The set becomes empty - No parameters needed
codemon_types = {'water', 'fire', 'plant', 'electric'} print("Original set:", codemon_types) removed = codemon_types.pop() print(f"Removed element: {removed}") print("After pop():", codemon_types) # Try running multiple times - different element each time! removed2 = codemon_types.pop() print(f"Removed another: {removed2}") print("After second pop():", codemon_types)
codemon_team = {'Aquachu', 'Pyrochu', 'Florachu'} print("Original team:", codemon_team) print("Size before:", len(codemon_team)) codemon_team.clear() print("\nAfter clear():", codemon_team) print("Size after:", len(codemon_team)) print("Is empty?", len(codemon_team) == 0)
pop() is Unpredictable
Unlike lists where
pop()
removes the last element, sets don't have order, so
pop()
removes an arbitrary element. Each time you run the code, a different element might be removed! Don't use
pop()
if you need to remove a specific element.
Exercise 9 — Understanding pop() Behavior
What is the key characteristic of the
pop()
method when used with sets?
Options
• It removes and returns an arbitrary (random) element from the set
• It always removes the first element that was added to the set
• It removes the element with the smallest value
• It removes the last element that was added to the set
Hint : Think about the fundamental property of sets - they are unordered collections. How would this affect which element gets removed?
Exercise 10 — Match Set Methods with Their Behaviors
Match each set method with its correct description:
Items to match
• add()
• update()
• remove()
• discard()
• pop()
• clear()
Definitions
• Adds a single element to the set
• Adds multiple elements from an iterable
• Removes element, raises error if not found
• Removes element, no error if not found
• Removes and returns arbitrary element
• Removes all elements from the set
Exercise 11 — Comprehensive Understanding Check
What will be the final output of this code?
codemon_set = {'Aquachu', 'Pyrochu'} codemon_set.add('Florachu') codemon_set.update(['Zap', 'Aquachu']) codemon_set.discard('Rockachu') codemon_set.remove('Pyrochu') print(len(codemon_set))
Options
• ```3```
• ```4```
• ```5```
• An error will occur
Hint : Trace through each operation carefully. Remember that sets maintain uniqueness, discard doesn't error on missing elements, and remove does remove existing elements.
Exercise 12 — Build Your Battle Team
You're preparing for a tournament and need to build your perfect battle team! 1. Add a new Codémon named 'Zap' to your team 2. You found 3 more Codémon in the wild: 'Florachu', 'Shadowchu', and 'Aquachu' - add them all at once 3. Remove 'Rockachu' from your team (you're sure it's there) 4. Try to remove 'Pyrochu' (you're not sure if it's in the team) 5. Display your final team and count
Starter code
battle_team = {'Aquachu', 'Pyrochu', 'Rockachu'} print("=== BUILDING BATTLE TEAM ===") print("Starting team:", battle_team) # 1. Add Zap # 2. Add multiple Codémon from the wild # 3. Remove Rockachu (we're sure it's there) # 4. Try to remove Pyrochu (not sure if it exists) # 5. Display final team print("\n=== FINAL BATTLE TEAM ===") print("Team:", battle_team) print(f"Total members: {len(battle_team)}")
Back to the course