Python Sets
A set is a collection that holds each item only once. A set makes no promise about order.
A set drops duplicates
You write a set with curly brackets. Python drops the repeat on its own.
colors = {"red", "blue", "red", "green"}
print(len(colors))Make a set from a list
Use set() to turn a list into a set.
numbers = [4, 2, 4, 2, 7]
unique = set(numbers)
print(sorted(unique))Sort before you print
A set keeps no promised order. Use sorted() when you need a stable order.
letters = {"b", "a", "c"}
print(sorted(letters))An empty set
Curly brackets alone make an empty dict. Use set() for an empty set.
empty = set()
print(len(empty))Example
names = ["Mia", "Liam", "Mia", "Noah", "Liam", "Ava"]
unique_names = set(names)
print("Unique names:", len(unique_names))
print(sorted(unique_names))Key points
- Set: a collection that holds each item only once
- Use { } to write a set with items inside it
- Use set() to build a set from a list
- Use len() to count how many items a set holds
- Lists keep ordered items.
In this example, names is a list with some repeats. The set() call builds a set from the list. Each repeat drops away at that step. The len() call counts the four names left. The sorted() call prints the names in a stable order.
Note
{ } makes an empty dict, not an empty set — use set() for an empty set
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does len({"a", "b", "a"}) give?