How to Create a Set in Python
A set is a collection in which every item appears once. It's the right container for things like "the file extensions we accept", where duplicates make no sense and the question you ask is "is this one of them?". This guide creates a set, adds to it and makes an empty one on Python 3.15.2.
Syntax
{<item>, <item>, ...}
set(<iterable>)
| Part | What it means |
|---|---|
{<item>, <item>, ...} | A set written out, with its items between curly braces |
set(<iterable>) | A set made from the items of a list, a string or anything else you can loop over |
set() | With nothing inside the brackets: an empty set |
The Python tutorial describes a set as "an unordered collection with no duplicate elements", and says: "Curly braces or the set() function can be used to create sets."
The Example
A set of image widths, written with one width twice. The script prints the set and its size, adds a width, and makes an empty set.
Prerequisites
- uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
sizes = {240, 320, 500, 320}
print(sizes)
print(len(sizes))
sizes.add(640)
print(sizes)
empty = set()
print(empty)

Step 2: Run It
uv run python sets.py
{240, 320, 500}
3
{240, 320, 500, 640}
set()

The second 320 is gone: a set keeps one of each, so len() counts 3 items, not 4. add() put 640 in, and an empty set prints as set(). The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Making an empty set with {} | type({}) printed <class 'dict'>: empty curly braces make a dictionary | Use set() |
Putting a list into a set: {[1, 2]} | TypeError: cannot use 'list' as a set element (unhashable type: 'list') | Use a tuple, which can't change: {(1, 2)} printed {(1, 2)} |
| Relying on the order of a set | Sets have no order you can count on | Use sorted(the_set) when you need one |
The tutorial warns about the first one: "to create an empty set you have to use set(), not {}; the latter creates an empty dictionary". And about the last: "Because sets are unordered, iterating over them or printing them can produce the elements in a different order than you expect."
FAQ
How do I remove the duplicates from a list?
Turn it into a set: set([3, 1, 3]) printed {1, 3}. Turn the result back into a list with list() if you need one.
What is a set good for?
Checking whether something is in it, with in, and comparing groups: the tutorial lists "membership testing and eliminating duplicate entries" as its basic uses.
Conclusion
{240, 320, 500, 320} made a set of three widths, because a set keeps each item once, and add() added a fourth. An empty set is set(), never {}, and only items that can't change, such as numbers, strings and tuples of them, can go into one.
