Lesson 7 of 10
A set is an unordered collection where every value appears once. Duplicates are dropped automatically.
numbers = {1, 2, 3, 2, 1}
print(numbers)
print(len(numbers))
Curly braces, like a dictionary, but with single values instead of key: value pairs.
One catch: {} creates an empty dictionary, not an empty set. For an empty set you need
set().
empty_dict = {}
empty_set = set()
print(type(empty_dict))
print(type(empty_set))
Removing duplicates
The most common everyday use of a set is deduplicating a list:
names = ["ada", "grace", "ada", "alan", "grace"]
unique = set(names)
print(len(unique))
print(sorted(unique))
Sets have no order, so printing one directly can surprise you. Wrap it in sorted() when you
want predictable output.
Adding and removing
colours = {"red", "green"}
colours.add("blue")
colours.discard("red")
colours.discard("purple")
print(sorted(colours))
.add() adds one item. .remove() deletes an item but raises KeyError if it's missing;
.discard() does the same thing but stays quiet when the item isn't there.
Set operations
This is where sets shine — comparing two collections.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
print(sorted(a ^ b))
| Operator | Name | Meaning |
| --- | --- | --- |
| \| | union | in either set |
| & | intersection | in both sets |
| - | difference | in the first but not the second |
| ^ | symmetric difference | in one but not both |
Each has a method spelling too — a.union(b), a.intersection(b), and so on.
Fast membership testing
Checking x in mylist gets slower as the list grows, because Python scans it item by item.
Checking x in myset stays fast no matter how big the set is. For large collections you only
need to search, a set is the right tool.
allowed = {"ada", "grace", "alan"}
print("ada" in allowed)
print("bob" in allowed)
Limits
Sets are unordered, so there is no indexing — myset[0] is an error. Their items must also be
immutable, for the same reason dictionary keys must be.
Try it yourself
Print the union, intersection, and difference of the two sets, sorted each time.
Checkpoint
- Sets hold unique, unordered values;
set(mylist)deduplicates. {}is an empty dictionary — useset()for an empty set.|,&,-,^are union, intersection, difference, symmetric difference.- Membership testing is fast, but there is no indexing or order.
Questions about this lesson
Log in to ask a question.