Sets in practice
🌍 In real life. A teacher checks a homework rule: "Use every vowel at least once." Another asks: "Did anyone hand in twice?" And a shop keeps the order customers came in, but only wants each customer once. These are everyday jobs where "one of each" is the whole point.
This lesson puts sets to work on jobs like these.
The idea in one sentence: compare whole sets with == and <=, find repeats by comparing len(set(x)) with len(x), and pair a seen set with a list when the order matters.
Its words:
- subset:
a <= bis True when every value of a is also in b - equal sets:
{1, 2} == {2, 1}is True: the same values, order doesn't matter - order-keeping dedupe: remove repeats but keep the first-seen order, using a set and a list together
Step by step, does "hello" repeat a letter?
set("hello")keeps h, e, l, o: 4 different letters.len("hello")is 5.- 4 isn't 5, so some letter repeats.
print({1, 2} == {2, 1})
print({"a"} <= {"a", "b"})
print({"c"} <= {"a", "b"})set(word) gives the different letters of a word, so it's quick to check things like "does this word repeat a letter?"
word = input("Word: ")
print(len(set(word)) == len(word))A set forgets the order, so to remove repeats and keep the order, use a seen set together with a list:
words = ["b", "a", "b", "c", "a"]
seen = set()
order = []
for w in words:
if w not in seen:
seen.add(w)
order.append(w)
print(order)word = input("Word: ")
print({"a", "e", "i", "o", "u"} <= set(word))A set that can't change: frozenset. A set can't be a dictionary key or sit inside another set, because it can change: {{1, 2}: "x"} gives TypeError: cannot use 'set' as a dict key (unhashable type: 'set'). A frozenset is a set that never changes. It has in, len, |, & and <=, but no add or remove, so it can be a key: for example the ingredients of a dish, whatever order they are listed in.
menu = {frozenset({"rice", "dal"}): "khichuri", frozenset({"rice", "egg"}): "egg fried rice"}
have = frozenset({"dal", "rice"})
print(menu[have])
print("egg" in have, len(have))What it costs. Turning a list into a set takes one pass over the list. After that, each in is a fast hash lookup. Compare the two ways to check a list of n names for repeats:
- with a nested loop, comparing every name with every other: about n × n comparisons; for 10,000 names, 100 million
- with a
seenset: one pass, about 10,000 quick lookups
Mistakes and edge cases.
- Losing the order.
list(set(words))removes repeats but scrambles the order; use theseen+ list pattern above. - Indexing the result.
set(names)[0]givesTypeError: 'set' object is not subscriptable. - < and <=.
a < bmeans a is a subset and smaller than b, so{1} < {1}is False, while{1} <= {1}is True. - Letters, not words.
set("a cat")holds the letters and the space, not the words; useset(text.split())for words.
Quiz
What does this print?
print({3, 1} == {1, 3})What does this print?
print({"a", "b"} <= {"a"})What does this print?
seen = set() order = [] for w in ["x", "y", "x"]: if w not in seen: seen.add(w) order.append(w) print(order)Why use a set for
seeninstead of a list?- Checking `in` a set is very fast, and repeats are dropped anyway
- A set keeps the order of the items
- Lists can't use `in`
What does this print?
print(len(set([1, 1, 2]) | {3}))Which line stops this program with an error?
names = ["Bo", "Ana", "Bo"] unique = set(names) print(unique[0])
Coding tasks
Ask for some words on one line. Print them without repeats, keeping the order in which each word first appeared, on one line separated by spaces.
Ask for a word. Print
Trueif no letter appears twice in it, otherwiseFalse.Ask for a sentence in lowercase. Print
Trueif it uses all five vowels (a, e, i, o, u) somewhere, otherwiseFalse.