Python · Sets
Intro to Sets
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — What is a Set?
A set is a collection of unique elements in Python. The most important characteristic of a set is that it automatically removes duplicates - each element can only appear once.
Sets are created using curly braces
{}
or the
set()
function:
# Creating a set of Codémon types
codemon_types = {'water', 'fire', 'plant'}
print(codemon_types)
print(type(codemon_types))
Notice how the set contains unique values. If we try to add duplicates, the set will keep only one copy of each element.
Sets are Unordered
Unlike lists, sets don't maintain any specific order. The elements might appear in a different order each time you print the set.
Exercise 2 — The Power of Uniqueness
The uniqueness property of sets is what makes them special. When you create a set with duplicate values, Python automatically keeps only one copy of each element.
codemon_list = ['Aquachu', 'Pyrochu', 'Aquachu', 'Florachu', 'Aquachu']
print('Original list:', codemon_list)
print('Number of items:', len(codemon_list))
# Convert to set - duplicates are removed
codemon_set = set(codemon_list)
print('\nAs a set:', codemon_set)
print('Number of unique items:', len(codemon_set))
In this example:
- The list has 5 items (with duplicates)
- The set has only 3 items (unique values only)
- All duplicate 'Aquachu' entries were automatically removed
Practical Use Case
Sets are perfect when you need to find unique values in a collection, like counting how many different types of Codémon a trainer has caught, regardless of how many of each type they have.
Exercise 3 — Understanding Set Uniqueness
Given the following code, what will be the output?
types = {'fire', 'water', 'fire', 'plant', 'water', 'fire'}
print(len(types))
Options
• ```3```
• ```6```
• ```5```
• ```An error will occur```
Hint : Remember that sets automatically remove duplicates. Count how many unique values are in the set.
Exercise 4 — Different Ways to Create Sets
There are two main ways to create sets in Python:
- Using curly braces
{}
- Using the
set()
constructor
codemon_set1 = {'Aquachu', 'Pyrochu', 'Florachu'}
print('Method 1:', codemon_set1)
codemon_list = ['Aquachu', 'Pyrochu', 'Florachu']
codemon_set2 = set(codemon_list)
print('Method 2:', codemon_set2)
Common Pitfall: Empty Sets
To create an empty set, you MUST use
set()
. Using
{}
creates an empty dictionary, not an empty set!
You can also create a set from any iterable (list, tuple, string):
letters = set('Aquachu') # From a string
print('Letters in Aquachu:', letters)
# From a tuple
codemon_tuple = ('fire', 'water', 'fire', 'plant')
unique_types = set(codemon_tuple)
print('Unique types:', unique_types)
Exercise 5 — Creating Empty Collections
Which of the following correctly creates an empty set?
Options
• ```empty_set = set()```
• ```empty_set = {}```
• ```empty_set = []```
• ```empty_set = set([])```
Hint : Remember that {} creates an empty dictionary, not a set. Think about the correct syntax for creating an empty set.
Exercise 6 — Sets vs Lists: Key Differences
While both sets and lists are collections in Python, they have important differences. Lists are ordered and allow duplicate elements, while sets are unordered and only store unique elements.
codemon_list = ['Aquachu', 'Pyrochu', 'Aquachu']
print('List:', codemon_list)
print('First item:', codemon_list[0]) # Can access by index
print('Length:', len(codemon_list)) # Counts duplicates
codemon_set = {'Aquachu', 'Pyrochu', 'Aquachu'}
print('\nSet:', codemon_set)
print('Length:', len(codemon_set)) # Only unique items
# print(codemon_set[0]) # This would cause an error!
Key differences:
Lists:
- Maintain order of elements
- Allow duplicate values
- Can access elements by index:
my_list[0]
- Use square brackets:
[]
Sets:
- Don't maintain order
- Only unique values
- Cannot access by index
- Use curly braces:
{}
When to Use Each
Use lists when:
- Order matters
- You need to access elements by position
- Duplicates are meaningful
Use sets when:
- You only care about unique values
- Order doesn't matter
- You need to check membership quickly
Exercise 7 — Create Your First Set
Complete the code to create a set of Codémon types and then convert a list with duplicates into a set.
# List with duplicates
caught_types = ['fire', 'water', 'fire', 'plant', 'water']
# Convert list to set to get unique types
unique_types = ____(____)
print('Unique caught types:', unique_types)
Options: set caught_types list
Hint : Remember: sets are created with curly braces, and you can convert other collections to sets using the set() function.
Exercise 8 — Match Code with Output
Match each piece of code with its output:
Items to match
• len({'fire', 'water', 'plant'})
• len({'fire', 'fire', 'water'})
• type({})
• type(set())
Definitions
• 3
• 2
• <class 'dict'>
• <class 'set'>
Exercise 9 — Choosing the Right Data Structure
A trainer wants to keep track of all the different types of Codémon they've encountered, without counting duplicates. Which data structure should they use?
Options
• A set, because it automatically keeps only unique values
• A list, because it maintains the order of encounters
• A string, because it's easy to read
• A tuple, because it's immutable
Hint : Think about which data structure's main characteristic matches the requirement of 'without counting duplicates'.
Exercise 10 — Finding Unique Values
Complete the code to find how many unique Codémon types are in the trainer's collection.
# Trainer's collection with many duplicates
collection = ['fire', 'water', 'fire', 'plant', 'water', 'fire', 'electric', 'water']
# Convert to set to get unique types
unique_types = ____(____)
# Count unique types
count = ____(unique_types)
print(f'The trainer has {count} unique types')
print('Types:', unique_types)
Options: set collection len list unique_types count
Hint : Think about how to convert a list to a set, and how to count the number of elements in a collection.
Exercise 11 — Set Characteristics
Match each characteristic with the correct data structure:
Items to match
• Automatically removes duplicates
• Elements can be accessed by index
• Created with curly braces and no duplicates
• Maintains insertion order
Definitions
• Set
• List
• Set
• List
Exercise 12 — Codémon Collection Analysis
You've been catching Codémon all day and your collection has many duplicates!
Convert your collection list to a set to find out how many unique types you've caught, then display them.
Starter code
caught_today = ['fire', 'water', 'fire', 'plant', 'water', 'electric', 'fire', 'water', 'plant', 'ice', 'fire']
print("=== DAILY CATCH REPORT ===")
print(f"Total catches: {len(caught_today)}")
# Convert to set to get unique types
# Display results
Back to the course