Python Sets in Practice
What you will learn
- When a set beats a list: speed and uniqueness
- Counting distinct items and detecting duplicates
- Filtering with a set of unwanted items
- Comparing two collections: added, removed, kept
- Validating with required fields and permissions
- Measuring similarity, and tracking visited items
- When not to use a set
Lessons 10.1 and 10.2 showed how sets work. This lesson shows what they are good for. The rule of thumb: reach for a set when the question is "is it in there?", "what is different?" or "how many different?", and you do not care about order or repeats.
1. Fast membership tests
Asking x in a_list looks at the items one by one. Asking x in a_set goes straight to the answer (lesson 9.7). It makes no difference for ten items, and a huge difference for a million.
A test on one computer: keeping the numbers of a (10,000 of them) that are also in b (another 10,000) took far longer when b was a list than when it was a set. The set version was more than 20 times quicker, and the answers were the same.
a = list(range(10000))
b = list(range(5000, 15000))
slow = [x for x in a if x in b] # b is a list: searched item by item
bs = set(b)
fast = [x for x in a if x in bs] # bs is a set: direct lookup
print(len(fast), slow == fast)
5000 True
The habit: if you test membership many times, turn the collection into a set once, before the loop.
Quick check: you test thousands of words against a list of 50,000 allowed words. What should you do first?
Convert the allowed words to a set once: allowed = set(words), and test against that.
2. Distinct items and duplicates
words = "the cat sat on the mat the dog sat on the log".split()
print(len(words), len(set(words)))
print(sorted(set(words)))
12 7
['cat', 'dog', 'log', 'mat', 'on', 'sat', 'the']
Twelve words, but only seven different ones. A test for any duplicates compares the lengths:
def has_duplicates(items):
return len(set(items)) != len(items)
print(has_duplicates([1, 2, 3]), has_duplicates([1, 2, 1]), has_duplicates("hello"))
False True True
To find the first repeat, remember what you have seen and stop at the first match:
def first_duplicate(items):
seen = set()
for x in items:
if x in seen:
return x
seen.add(x)
return None
print(first_duplicate([3, 1, 4, 1, 5]), first_duplicate([1, 2]), first_duplicate("abca"))
1 None a
(def and return are chapter 11.) This seen-set pattern is one of the most useful in programming.
3. Filtering with a stop-list
To remove unwanted items, keep a set of them and test against it:
stop = {"the", "on", "a"}
kept = [w for w in words if w not in stop]
print(kept)
print(len(set(kept)))
['cat', 'sat', 'mat', 'dog', 'sat', 'log']
5
The list keeps the order and repeats of the words that remain. The set at the end counts the distinct ones.
4. What changed? Added, removed, kept
Comparing "before" and "after" is a classic. Three differences answer it (lesson 10.2):
ids_old = {1, 2, 3, 4}
ids_new = {3, 4, 5}
print("added", sorted(ids_new - ids_old))
print("removed", sorted(ids_old - ids_new))
print("kept", sorted(ids_old & ids_new))
added [5]
removed [1, 2]
kept [3, 4]
The same idea finds new customers, deleted files, or lines that differ between two lists.
5. Validating: required fields and permissions
Subset tests check that everything needed is there:
required = {"name", "email"}
given = {"name", "age"}
print(sorted(required - given))
print(required <= given)
['email']
False
required - given lists what is missing, and required <= given asks whether nothing is missing. The same works for permissions:
permissions = {"alice": {"read", "write"}, "bob": {"read"}}
need = {"read", "write"}
print({u: need <= p for u, p in permissions.items()})
print({u: sorted(need - p) for u, p in permissions.items()})
print(sorted(set.union(*permissions.values())))
print(sorted(set.intersection(*permissions.values())))
{'alice': True, 'bob': False}
{'alice': [], 'bob': ['write']}
['read', 'write']
['read']
Alice has everything she needs, and Bob lacks write. The last two lines show what anyone can do, and what everyone can do.
6. Measuring similarity
The Jaccard index measures how alike two sets are: the size of the overlap divided by the size of the union. It is 1.0 for identical sets and 0.0 for sets with nothing in common:
def jaccard(a, b):
a, b = set(a), set(b)
return len(a & b) / len(a | b) if a | b else 1.0
print(jaccard("night", "nacht"))
print(jaccard({1, 2, 3}, {2, 3, 4}))
print(jaccard("abc", "abc"), jaccard("abc", "xyz"))
0.42857142857142855
0.5
1.0 0.0
"night" and "nacht" share the letters n, h and t (3 letters) out of 7 different letters altogether, which is 3/7. Applied to sets of words, it gives a rough measure of how similar two texts are:
text1 = "the quick brown fox jumps"
text2 = "the lazy brown dog sleeps"
w1 = set(text1.split())
w2 = set(text2.split())
print(sorted(w1 & w2))
print(round(len(w1 & w2) / len(w1 | w2), 3))
['brown', 'the']
0.25
7. Tracking visited items
When walking through a map, a maze or a web of links, keep a set of places already seen, so that you never go round in circles:
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "A"], "D": []}
visited = set()
stack = ["A"]
order = []
while stack:
node = stack.pop()
if node in visited:
continue
visited.add(node)
order.append(node)
stack.extend(reversed(graph[node]))
print(order)
print(sorted(visited))
['A', 'B', 'D', 'C']
['A', 'B', 'C', 'D']
Without visited, the link from C back to A would make the loop run forever. (This is a depth-first search; the stack idea is lesson 7.6.)
Sets of tuples: cells on a grid
Tuples are hashable, so a set of coordinates is a simple way to hold points:
cells = {(0, 0), (0, 1), (1, 1)}
print((0, 1) in cells, (5, 5) in cells, len(cells))
def neighbours(cell):
x, y = cell
return {(x + dx, y + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (dx, dy) != (0, 0)}
print(len(neighbours((0, 0))))
print(sorted(neighbours((0, 0)) & cells))
True False 3
8
[(0, 1), (1, 1)]
The last line finds which neighbours of the cell (0, 0) are in the set.
8. Normalise, then take distinct
Before you count distinct items, make equal things look equal:
emails = ["a@x.com", "B@x.com", "a@x.com", "b@x.com"]
unique = {e.lower() for e in emails}
print(sorted(unique), len(unique))
['a@x.com', 'b@x.com'] 2
Without .lower() there would be three different emails, because B@x.com and b@x.com differ.
A set can also check coverage. A pangram uses every letter of the alphabet:
alphabet = set("abcdefghijklmnopqrstuvwxyz")
print(alphabet <= set("thequickbrownfoxjumpsoverthelazydog"))
print(set("hello") <= alphabet, set("hello!") <= alphabet)
True
True False
9. When not to use a set
| You need | Use instead |
|---|---|
| to keep the order | a list (or dict.fromkeys to dedupe in order) |
| to keep repeats and count them | a list, or Counter (lesson 9.6) |
| items that are not hashable (lists, dicts) | a list, or convert items to tuples |
| to read items by position | a list or tuple |
| values attached to keys | a dictionary |
A set is not a faster list. It is a different tool, and the right one only when uniqueness and membership are what matter.
Worked example: a guest list check
Invitations went to some people, and some replied. Find who has not replied, who came without an invitation, and how many different people are involved.
invited = ["Rina", "Sam", "Lee", "Mia", "Tom"]
replied = ["Sam", "Lee", "Zoe", "Sam"]
arrived = ["Lee", "Zoe", "Rina", "Lee"]
inv, rep, arr = set(invited), set(replied), set(arrived)
print("not replied:", sorted(inv - rep))
print("replied but not invited:", sorted(rep - inv))
print("arrived uninvited:", sorted(arr - inv))
print("replied yes and arrived:", sorted(rep & arr))
print("different people:", len(inv | rep | arr))
not replied: ['Mia', 'Rina', 'Tom']
replied but not invited: ['Zoe']
arrived uninvited: ['Zoe']
replied yes and arrived: ['Lee', 'Zoe']
different people: 6
| Question | Operation |
|---|---|
| who has not replied? | inv - rep |
| who replied without an invitation? | rep - inv |
| who turned up uninvited? | arr - inv |
| who replied and came? | rep & arr |
| how many different people? | size of the three-way union |
Repeats (Sam replied twice, Lee arrived twice) are dropped automatically. The names are made up.
Common mistakes
- Testing membership against a long list inside a loop. Convert it to a set first.
- Forgetting to normalise (case, spaces) before taking distinct items.
- Using a set when order or repeats matter.
- Putting unhashable items in a set. Use tuples.
- Looping over a set and expecting a fixed order (lesson 10.1).
Key takeaways
- Use a set for fast membership, distinct counts, duplicate checks and "what differs?" questions.
len(set(x)) != len(x)tests for duplicates; a seen set finds the first repeat.new - oldis added,old - newis removed,old & newis kept.required <= givenandrequired - givenvalidate that everything needed is present.- A set of visited places stops loops; a set of tuples holds grid cells; normalise values before taking distinct ones.
- Do not use a set when you need order, repeats or unhashable items.
Practice
1. How many different words are in "to be or not to be"?
Show answer
len(set("to be or not to be".split())) is 4 (the words to, be, or and not).
2. old = {1, 2, 3}, new = {2, 3, 4}. Which items were added and which removed?
Show answer
Added: new - old is {4}. Removed: old - new is {1}.
3. Write a test that is true when every item of needed is in have.
Show answer
needed <= have (or needed.issubset(have)).
4. Why convert a list of 100,000 allowed names to a set before testing thousands of names against it?
Show answer
Each test against a list searches item by item, while a set answers directly. One conversion is far cheaper than thousands of long searches.
5. What is the Jaccard index of {1, 2} and {2, 3}?
Show answer
The overlap {2} has 1 item and the union {1, 2, 3} has 3, so it is 1/3, about 0.333.
6. Name two situations where a list is better than a set.
Show answer
When the order matters, or when repeats matter (you need to keep or count duplicates). Also when you must read items by position.