12.6 Set Indexing and Ordering
Why s[0] raises TypeError on a set -- elements are located by hash, not by integer position -- and why iteration order is an implementation detail of the hash table layout, never something to rely on.
Why Sets Don’t Support Indexing
Sets have no concept of position — elements are located by hash, not by an integer offset, so s[0] is meaningless and raises TypeError.
>>> s = {3, 1, 2}
>>> s[0]
Traceback (most recent call last):
TypeError: 'set' object is not subscriptable
Iteration Order
The order elements appear when iterating a set is an implementation detail of the hash table layout, not insertion order — it can look consistent within one run but should never be relied upon.
>>> list({3, 1, 2}) # order here is incidental, not guaranteed by the language
[1, 2, 3]
Hashing Concept
Every element’s position in the underlying table is derived from hash(element) (see 12.3 Internal Representation) — this is exactly why set elements must be hashable, and why sets can’t contain lists or dicts.
Quick Interview Answer
“A set has no indexing because it has no positions — every element lives in a slot determined by its hash, not by where it was inserted, so
s[0]raisesTypeError: 'set' object is not subscriptable. The same reasoning explains iteration order: what you see when you loop over a set reflects the hash table’s internal layout, not insertion order, and while it can look stable within a single run, it is not something the language guarantees — sort explicitly withsorted(my_set)whenever the output order actually matters.”
Common Mistakes
- Writing
s[0]or slicing a set (s[:2]) out of list habit — neither works; convert to asorted()list first if positional access is genuinely needed. - Assuming
list(some_set)reproduces insertion order — it reflects hash-table layout instead, and can differ across Python versions or even between runs for certain types. - Relying on set iteration order in a script’s output, then being confused when it “changes” — it was never guaranteed to begin with.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form