Skip to main content

Python Sets

Satellite · Data Types

Python Sets

Sets track unique elements and support fast membership checks. Use them for deduplication, tagging, and math-like operations.

Creation

items = {1, 2, 3}
empty = set() # {} makes an empty dict, not a set
deduped = set(["a", "b", "a"]) # {'a', 'b'} — duplicates dropped

Two defining traits:

  • Elements are unique — adding a duplicate is a no-op.
  • Sets are unordered — they have no index, so items[0] raises TypeError.

Elements must be hashable (immutable), so you can store numbers, strings, and tuples, but not lists or dicts.

Adding and removing

s = {1, 2}
s.add(3) # {1, 2, 3}
s.discard(9) # no error if missing
s.remove(2) # KeyError if missing
s.pop() # remove and return an arbitrary element

Operations

a = {1, 2, 3}
b = {3, 4, 5}
a | b # union -> {1, 2, 3, 4, 5}
a & b # intersection -> {3}
a - b # difference -> {1, 2}
a ^ b # symmetric diff -> {1, 2, 4, 5}

Each operator has a method form (a.union(b), a.intersection(b)) that accepts any iterable, not just another set.

Membership checks are O(1) on average—far faster than scanning a list:

if email in unsubscribed:   # instant, even for millions of entries
skip(email)

Subset and superset tests

{1, 2} <= {1, 2, 3}    # True — subset
{1, 2, 3} >= {1, 2} # True — superset
{1, 2}.isdisjoint({3}) # True — no elements in common

Set comprehensions

squares = {n * n for n in range(6)}          # {0, 1, 4, 9, 16, 25}
first_letters = {name[0] for name in names} # unique initials

Frozenset

frozenset is an immutable set. Because it is hashable, you can use it inside another set or as a dictionary key—something a regular set cannot do.

tags = frozenset({"python", "beginner"})
index = {tags: "article-1"} # frozenset as a dict key

Next up in your learning path

Frequently Asked Questions

How do I create an empty set in Python?

Use set(). The literal {} creates an empty dictionary, not a set, because dictionaries also use curly braces. Only non-empty sets like {1, 2} can use brace syntax.

empty = set()      # empty set
type({}) # <class 'dict'> — not a set!

Do Python sets keep their order?

No. Sets are unordered and have no index, so you cannot rely on element order or do set[0]. If you need order plus uniqueness, use dict.fromkeys(items) to deduplicate while preserving insertion order.

list(dict.fromkeys(["b", "a", "b", "c"]))   # ['b', 'a', 'c']

Why can I not add a list to a set?

Set elements must be hashable, and lists are mutable and therefore unhashable. Convert the list to a tuple first (or use a frozenset) if you need to store it in a set.

{[1, 2]}          # TypeError: unhashable type: 'list'
{(1, 2)} # OK — tuples are hashable

When should I use a set instead of a list?

Use a set when you need unique elements or fast membership tests (in is O(1) for sets vs O(n) for lists). Use a list when order matters or duplicates are meaningful.