2/40
Part 1 of 7 · Sets and seen-setsLearn and do

A set finds a value without a scan

Many coding questions get easy once you can answer one question fast: have I seen this before? A list answers it slowly. A set or a dict answers it in about the same time, whether it holds ten items or ten million.

A list checks every item, and a set looks in one place

ids = list(range(n))
id_set = set(ids)

# compares -1 with all n elements
-1 in ids
# hashes -1, then looks in one place
-1 in id_set

Each row below looks for -1, which isn't there, so the list has to check everything.

Predict

-1 in a list of 1,000 took 3.7 µs. About how long in a list of 1,000,000?

Pick an answer above to see the rest