Working with sets¶
In this tutorial, you will learn how to create and use sets — Python's collection for storing unique items.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Completion of Working with lists, Working with tuples, and Working with dictionaries
Learning objectives¶
By the end of this tutorial, you will be able to:
- Create sets and add or remove items
- Perform set operations such as union, intersection, and difference
- Test for subsets and supersets
- Use sets for practical tasks like removing duplicates
What is a set?¶
A set is an unordered, mutable collection of unique items. Sets automatically eliminate duplicates and provide fast membership testing.
Sets are created using curly braces {}:
fruits = {"apple", "banana", "cherry"}
print(fruits)
print(type(fruits))
You can also create a set from a list using set(). Notice how duplicates are removed automatically:
numbers = set([1, 2, 2, 3, 3, 3])
print(numbers)
Important: An empty {} creates an empty dictionary, not an empty set. Use set() to create an empty set:
empty_dict = {}
empty_set = set()
print(type(empty_dict)) # dict
print(type(empty_set)) # set
Adding items¶
Use add() to add a single item to a set:
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)
Adding an item that already exists has no effect — sets guarantee uniqueness:
fruits.add("apple")
print(fruits) # "apple" is not duplicated
Use update() to add multiple items at once:
fruits = {"apple"}
fruits.update(["banana", "cherry", "date"])
print(fruits)
Removing items¶
Use remove() to remove an item. This raises a KeyError if the item does not exist:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
Use discard() to remove an item without raising an error if it is missing:
fruits = {"apple", "cherry"}
fruits.discard("grape") # No error, even though "grape" is not in the set
print(fruits)
Set operations¶
Sets support mathematical set operations. Let us define two sets to work with:
maths_students = {"Alice", "Bob", "Charlie", "Diana"}
science_students = {"Charlie", "Diana", "Eve", "Frank"}
Union¶
The union combines all items from both sets (removing duplicates). Use | or union():
all_students = maths_students | science_students
print(f"All students: {all_students}")
Intersection¶
The intersection finds items common to both sets. Use & or intersection():
both = maths_students & science_students
print(f"In both classes: {both}")
Difference¶
The difference finds items in one set but not the other. Use - or difference():
maths_only = maths_students - science_students
print(f"Maths only: {maths_only}")
science_only = science_students - maths_students
print(f"Science only: {science_only}")
Symmetric difference¶
The symmetric difference finds items in either set, but not both. Use ^ or symmetric_difference():
exclusive = maths_students ^ science_students
print(f"In one class only: {exclusive}")
Subset and superset checks¶
Use issubset() to check whether all items in one set are contained in another:
small = {"Alice", "Bob"}
large = {"Alice", "Bob", "Charlie", "Diana"}
print(small.issubset(large)) # True
print(large.issuperset(small)) # True
Use isdisjoint() to check whether two sets have no items in common:
evens = {2, 4, 6}
odds = {1, 3, 5}
print(evens.isdisjoint(odds)) # True — no items in common
Frozen sets¶
A frozenset is an immutable version of a set. You cannot add or remove items from a frozenset, but you can use it as a dictionary key or as a member of another set:
vowels = frozenset({"a", "e", "i", "o", "u"})
print(vowels)
# Frozensets support set operations
consonants = frozenset({"b", "c", "d"})
print(vowels | consonants)
names = ["Alice", "Bob", "Alice", "Charlie", "Bob"]
unique_names = set(names)
print(unique_names)
If you need to preserve the original order, use dict.fromkeys() instead:
unique_ordered = list(dict.fromkeys(names))
print(unique_ordered)
Fast membership testing¶
Checking whether an item exists in a set is much faster than checking a list, especially for large collections:
allowed_users = {"alice", "bob", "charlie"}
username = "alice"
if username in allowed_users:
print(f"Welcome, {username}!")
else:
print("Access denied.")
Exercise: compare class lists¶
You have two lists of student names from different classes:
art_class = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
music_class = ["Charlie", "Eve", "Frank", "Grace"]
Using sets, find:
- Students who take both art and music
- Students who take art but not music
- All unique students across both classes
# Write your code here
Solution¶
Here is one way to complete the exercise:
art_class = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
music_class = ["Charlie", "Eve", "Frank", "Grace"]
art_set = set(art_class)
music_set = set(music_class)
# 1. Students in both classes
both = art_set & music_set
print(f"Both classes: {both}")
# 2. Art but not music
art_only = art_set - music_set
print(f"Art only: {art_only}")
# 3. All unique students
all_students = art_set | music_set
print(f"All students: {all_students}")
Summary¶
In this tutorial, you learned how to:
- Create sets using curly braces
{}andset() - Add items with
add()andupdate() - Remove items with
remove()anddiscard() - Perform union, intersection, difference, and symmetric difference
- Check for subsets, supersets, and disjoint sets
- Use frozen sets for immutable collections
- Remove duplicates and test membership efficiently
What is next¶
In the next tutorial, you will explore:
- Comprehensions — concise ways to build lists, dictionaries, and sets