Course outline · 0% complete

0/32 lessons0%

Course overview →

Sets and Choosing the Right Container

lesson 7-3 · ~11 min · 23/32

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_set stays fast even with millions of members. The same in on 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...UseExample
items in order, may changelistscores to append to
a fixed record, positions have meaningtuple(x, y) point
look up a value by a namedictname → age
uniqueness or fast in checkssetseen 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().