Sets

Python · Essentials · 6 min

Sets remove duplicates and answer 'is x in here?' in constant time.

A set holds unique, hashable items with no order: tags = {"python", "web"}. Like dict keys, membership tests x in s are O(1) on average, which makes sets the right choice whenever you check "have I seen this?" inside a loop. Note that {} is an empty dict; an empty set is written set().

set(iterable) deduplicates anything: set([1, 2, 2, 3]) == {1, 2, 3}. If you need to keep the original order while removing duplicates, use list(dict.fromkeys(items)) instead, since dicts are ordered.

Modify a set with add(x), discard(x) (no error if absent) and remove(x) (raises KeyError if absent).

Set algebra reads like maths and has operator and method forms:

  • a | b union, a & b intersection, a - b difference, a ^ b symmetric difference
  • a <= b subset, a >= b superset, a.isdisjoint(b)

The method forms (a.union(b), a.intersection(b)) accept any iterable, not just sets.

A frozenset is the immutable version. Because it's hashable, it can be a dict key or live inside another set, which a regular set can't.

Iteration order of a set is arbitrary and can differ between runs for strings (hash randomisation), so sort the set if you need stable output.

Example

seen = set()
for user in ["ana", "ben", "ana", "cy", "ben"]:
    if user in seen:
        print("duplicate:", user)
    seen.add(user)
print(sorted(seen))            # ['ana', 'ben', 'cy']

backend = {"python", "sql", "docker"}
frontend = {"js", "css", "docker"}
print(backend & frontend)      # {'docker'}
print(sorted(backend | frontend))
print(backend - frontend)      # {'python', 'sql'} (order may vary)

print(list(dict.fromkeys([3, 1, 3, 2, 1])))  # [3, 1, 2]
print(type({}), type(set()))   # <class 'dict'> <class 'set'>

Remember

  • Sets store unique hashable items with O(1) membership tests
  • {} is a dict; use set() for an empty set
  • Use | & - ^ for union, intersection, difference, symmetric difference

Watch out for

  • Relying on set iteration order.

Check yourself

  1. What does `len({1, 2} | {2, 3})` return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/tutorial/datastructures.html#sets