Sets: uniqueness for free
"Have I seen this before?" is one of the most common questions in code: has this email already been invited, has this page been visited, which distinct error codes occurred today. The set is the container built to answer it.
A set keeps each value at most once, with no positions at all. Build one with braces or by converting: set([1, 2, 2, 3]) is {1, 2, 3}. Careful: {} makes an empty dict, an empty set is set().
Two jobs sets do better than any other container, for concrete reasons:
- Deduplication: a set stores each value at most once by definition, so
set(words)drops every repeat in one step. - Fast membership: a set locates a value directly from the value itself instead of scanning item by item, so
x in my_setstays fast even with millions of members. The sameinon a list must walk the list front to back.
Sets also do math-style combinations: a & b keeps the common items, a | b merges both.
One string helper you will need here and in the projects: sentence.split() cuts a string into a list of words wherever there is whitespace:
"the cat sat".split() # ['the', 'cat', 'sat']
Code exercise · python
Run this. Sets have no reliable printing order, so we print lengths and sorted versions instead.
Quiz
You write `s = {}` intending to make an empty set. What did you actually make?
Which container do I reach for?
| You need... | Use | Example |
|---|---|---|
| items in order, may change | list | scores to append to |
| a fixed record, positions have meaning | tuple | (x, y) point |
| look up a value by a name | dict | name → age |
uniqueness or fast in checks | set | seen usernames |
Ask two questions: do I look things up by position, by key, or not at all? and does it need to change? The answers pick the container for you. When in doubt, start with a list and switch when a pattern from this table appears.
Quiz
You are tracking which email addresses have already been invited, and only ever ask "has this one been invited yet?". Best container?
Code exercise · python
Your turn. Print how many words the sentence has, then how many DIFFERENT words it has. Use split() and set().