When should you use a set instead of a list?
A set buys O(1) membership and pays for it by losing order and duplicates, and by requiring hashable elements. When you need the speed and the order, dict.fromkeys(seq) deduplicates in one pass and keeps insertion order.
Overview
What you gain and what you give up
Gain: membership in O(1) rather than O(n), and uniqueness enforced for free.
Give up: order, duplicates, indexing (s[0] is a TypeError), and the ability to hold unhashable elements. You cannot put a list in a set, though you can put a tuple.
Converting costs O(n), so a single membership test on a small list is not worth it. More than a couple of tests, or a large collection, and it is.
Step through it
What to watch
- The set is smaller: duplicates are gone, and so is the order.
dict.fromkeyskeeps both the order and the O(1) lookup.- All three hold the same distinct values.
Say this out loud
"Sets are for membership and uniqueness - O(1) instead of O(n). They lose order and need hashable elements. If I need dedup with order I use dict.fromkeys, since dicts have kept insertion order since 3.7."