Sets

Topic 4 of 5 in Collections5 min readBeginnerFree course

Overview

A set is a collection of unique items with no order. It answers questions like “have I seen this before?”, “which items are in both lists?” and “what are all the different values?” — quickly and in very little code.

Creating sets

Python
colours = {"red", "green", "blue"}
numbers = set([3, 1, 3, 2, 1])    # {1, 2, 3} — duplicates disappear
letters = set("hello")            # {'h', 'e', 'l', 'o'}
empty = set()                     # NOT {} — that's an empty dictionary

Two key properties:

  • No duplicates. Adding an item that’s already there does nothing. {1, 2, 2, 3} == {1, 2, 3}.
  • No order. There’s no first item and no indexing (colours[0] is a TypeError). When printed, items may appear in any order — use sorted(s) when the order matters for display.

Like dictionary keys, set items must be immutable: numbers, strings and tuples are fine; lists aren’t.

Removing duplicates

The most common use of a set:

Python
emails = ["a@x.com", "b@x.com", "a@x.com"]
unique = set(emails)          # {'a@x.com', 'b@x.com'}
print(len(unique))            # 2 different emails

If you need to keep the original order, use a dictionary instead (dictionaries keep insertion order and their keys are unique): list(dict.fromkeys(emails)).

Fast membership tests

x in my_list checks items one by one — slow for big lists. x in my_set uses a hash table and takes about the same time whether the set has ten items or ten million:

Python
banned = {"spam", "scam", "phish"}
if word in banned:
    print("Blocked")

If you check membership many times, convert the list to a set once first.

Changing a set

Python
tags = {"python"}
tags.add("web")            # add one item
tags.update(["api", "db"]) # add several
tags.discard("db")         # remove if present — no error if not
tags.remove("java")        # KeyError: 'java' — use discard if unsure
tags.clear()               # empty it

Set operations

Sets support the operations from maths, which make comparing groups easy:

Set operations on two overlapping groups: python = Asha, Ben, Chen, Dee and sql = Chen, Dee, Eli. python | sql is the union — everyone; python & sql is the intersection — Chen and Dee; python - sql is the difference — Asha and Ben; python ^ sql is the symmetric difference — those in exactly one group; and “Ben” in python is a fast membership test. Sets keep only unique items and have no order: {1, 2, 2, 3} == {1, 2, 3}.

Operator Method Result
a | b a.union(b) items in either
a & b a.intersection(b) items in both
a - b a.difference(b) in a but not b
a ^ b a.symmetric_difference(b) in exactly one
a <= b a.issubset(b) is every item of a also in b?
a >= b a.issuperset(b) does a contain all of b?
— a.isdisjoint(b) do they share nothing?
Python
python = {"Asha", "Ben", "Chen", "Dee"}
sql = {"Chen", "Dee", "Eli"}

python & sql      # {'Chen', 'Dee'}
python - sql      # {'Asha', 'Ben'}
sql - python      # {'Eli'} — difference depends on the order

The methods also accept lists: python.intersection(["Chen", "Zoe"]).

Real-world uses

Python
# Which required fields are missing from a form?
required = {"name", "email", "password"}
missing = required - set(form.keys())

# Which products are new this month?
new_products = set(this_month) - set(last_month)

# Do two users have any interests in common?
if user_a_interests & user_b_interests:
    print("You might get along!")

frozenset

A frozenset is an immutable set. You’ll rarely need it, but it can be a dictionary key or an item of another set: frozenset({"red", "blue"}).

Reach for a set when you hear: “unique”, “distinct”, “already seen”, “in common”, “missing”, or “difference between”.

Exercise

Course enrolments

Two courses have enrolment lists that contain some duplicates. Using sets: (1) print how many unique students each course has; (2) print, sorted, the students taking both courses; (3) the students taking Python but not SQL; (4) everyone, sorted; (5) the students in exactly one course; (6) check whether all of {"Asha", "Chen"} take Python using a subset test. Finally, remove duplicates from the tags list while keeping the original order (hint: dict.fromkeys).

Python
python = ["Asha", "Ben", "Chen", "Dee", "Asha", "Ben"]
sql = ["Chen", "Dee", "Eli", "Dee"]
tags = ["web", "python", "web", "api", "python", "data"]

# 1–6 with sets

# Remove duplicate tags, keeping order

Summary

  • A set holds unique items with no order: {1, 2, 3}; set() is the empty set ({} is an empty dict).
  • set(items) removes duplicates; x in s is very fast even for huge sets.
  • | union, & intersection, - difference and ^ symmetric difference compare groups.
  • add, discard and remove change a set; items must be immutable.
  • Sets have no positions or order — use sorted(s) for predictable output, and dict.fromkeys to de-duplicate while keeping order.