Skip to content
FollowtheDamnCode

Sets

Unique values, fast membership, and Venn-diagram maths.

4 minute read

Big idea

A set is a bag of unique values with no order. It removes duplicates automatically and answers "is this in here?" very fast.

Making a set

Duplicates disappear
colors = {"red", "green", "red", "blue", "green"}
print(len(colors))
print("red" in colors)
print(sorted(colors))
output
3
True
['blue', 'green', 'red']

Run and edit it in the app.

A set has no positions, so colors[0] is an error, and printing a set may show its items in any order. sorted(...) gives you a list in a fixed order when you need one.

An empty set is set() — because {} already means an empty dictionary (next lesson).

Removing duplicates

The most common use: turn a list into a set to drop repeats.

Predict: how many unique visitors?
visits = ["ana", "ben", "ana", "cy", "ben", "ana"]
unique = set(visits)
print(len(visits))
print(len(unique))
What does it print? Show the answer
6
3

Run and edit it in the app.

Adding and removing

tags = set()
tags.add("python")
tags.add("python")     # already there — nothing happens
tags.discard("java")   # remove if present; no error if not

Set maths

Sets can be combined like Venn diagrams:

Two clubs
chess = {"ana", "ben", "cy"}
drama = {"cy", "dee", "ana"}
print(sorted(chess & drama))
print(sorted(chess | drama))
print(sorted(chess - drama))
output
['ana', 'cy']
['ana', 'ben', 'cy', 'dee']
['ben']

Run and edit it in the app.

  • a & b — intersection: in both.
  • a | b — union: in either.
  • a - b — difference: in a but not b.

Fast membership

Checking x in some_list looks at items one by one. Checking x in some_set jumps almost straight to the answer, however big the set is — so when you'll check membership many times, use a set.

Fix the bug: count the different letters in "banana"
word = "banana"
print(len(word))
output
3

Run and edit it in the app.

What is len({1, 2, 2, 3, 3, 3})?

Watch it

Think of it like

A guest list at the door. Each name is on it once, the order doesn't matter, and the bouncer can tell you instantly whether someone's on it.

Key terms

  • Set — An unordered collection of unique values: {1, 2, 3}.
  • Union / intersection / difference — |, &, -: combining sets.
  • Membership test — x in s; very fast for sets.

Check yourself

What does set([1, 1, 2]) contain?

How do you make an empty set?

What is {1, 2, 3} & {2, 3, 4}?