Build with confidence · 15 min

Reason about performance

Choose a data structure based on the work you need to do.

A list membership check may examine every item, so its worst-case work grows with the list length, written as O(n). A set uses hashing, so membership usually takes roughly constant time, written as O(1) on average.

Building a set takes time and memory. It can pay off when you make many membership checks against the same collection. Build it once, outside the loop. When comparing speed, measure realistic inputs separately from setup.

Follow the example

Create the set once before checking multiple values.

Try it yourself

Use a set of known values from 0 through 9,999. Count how many of 1, 12,000, 6, and 9,999 are in the set.

Target output

3 matches
Show a hint

Build the set with set(range(10_000)), then reuse the membership expression.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
known = set(range(10_000))
queries = [1, 12_000, 6, 9_999]
matches = sum(item in known for item in queries)
print(f"{matches} matches")