12.18 Best Practices
When automatic deduplication and mathematical set operations make a set the right choice, why converting a checked-against collection to a set once pays off immediately, and a decision table for set vs. list vs. frozenset.
When to Use Sets
- Automatic deduplication is needed.
- Fast, repeated membership testing is needed.
- Mathematical set operations (union, intersection, difference) are needed.
Efficient Membership Tests
If a collection is checked with in more than a handful of times, convert it to a set once up front rather than testing against a list repeatedly (see 12.13 Performance).
# Less efficient -- O(n) per check, repeated many times
allowed = ["us-east-1", "us-west-2", "eu-west-1"]
for region in incoming_regions:
if region in allowed: # O(n) every single time
...
# More efficient -- convert once, O(1) per check afterward
allowed_set = set(allowed)
for region in incoming_regions:
if region in allowed_set: # O(1) average every time
...
Choosing Set vs. List vs. Frozenset
| Situation | Best choice |
|---|---|
| Order matters | list |
| Duplicates are meaningful | list |
| Need uniqueness + fast lookup | set |
| Need to be a dict key / set member | frozenset (not set) |
Quick Interview Answer
“The decision to reach for a set comes down to two questions: does this need to be deduplicated automatically, and will it be checked with
inmore than once or twice? If either is true, a set is the right default — and the moment a collection is checked repeatedly against a fixed set of allowed values, converting it to a set exactly once up front is one of the cheapest performance wins available. The one caveat: if that immutable, fixed collection itself needs to be a dict key or live inside another set,frozensetis the correct choice, not a regularset, since a plain set can never be hashed.”
Common Mistakes
- Testing membership against a list inside a loop that runs many times, instead of converting to a set once before the loop starts.
- Reaching for a set when the order elements were added actually matters for later output — a set silently discards that information.
- Using a regular
setas a dict key or as a member of another set and hittingTypeError: unhashable type: 'set'—frozensetis the type built for exactly that use case (see 12.11 Frozen Sets).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form