Sub topic 13
What you can and cannot assume about iteration order
This chapter assumes you know how a hash table stores entries in buckets, and that you can read basic Python. Iteration order is the sequence in which a loop visits the items of a set or map. Many bugs come from relying on an order that the language never promised.
Why hash tables have no natural order
A hash table places each key in a slot chosen by its hash. The slot depends on the hash value and the table size. It does not depend on the order you inserted keys or on how the keys compare. A plain traversal of the buckets therefore visits keys in an order that looks arbitrary. That order can also change when the table resizes, because every key is placed again in a larger array.
What languages actually promise
The guarantees differ by language and by structure. Check the documentation for the exact type you use.
| Structure | Iteration order |
|---|---|
| Python `dict` | Insertion order, guaranteed since Python 3.7 |
| Python `set` | Arbitrary. No guarantee |
| Java `HashMap` / `HashSet` | Unspecified |
| Java `LinkedHashMap` | Insertion order |
| Java `TreeMap` | Sorted by key |
| JavaScript `Map` and `Set` | Insertion order |
Python dicts keep insertion order by storing entries in a separate array and using the hash table only to find positions in that array. Re-assigning an existing key does not move it. Deleting a key and inserting it again puts it at the end.
d = {}
d["b"] = 1
d["a"] = 2
d["b"] = 3 # existing key keeps its position
print(list(d)) # ['b', 'a']
del d["b"]
d["b"] = 4 # re-inserted, so it goes last
print(list(d)) # ['a', 'b']Sets are different
A Python set has no order guarantee. Small integer sets often look sorted, because an integer hashes to itself. This is an accident of the implementation, so do not depend on it. String hashes are randomized per process, so the order of a set of strings can differ between runs.
tags = {"red", "green", "blue"}
for tag in tags:
print(tag) # order may change from one run to the nextIf you need a stable order from a set, sort it when you read it out. Use sorted(tags). If you need to keep insertion order and remove duplicates, use a dict, because its keys are unique and ordered.
items = ["b", "a", "b", "c", "a"]
print(list(dict.fromkeys(items))) # ['b', 'a', 'c']Common errors
- Writing a test that compares printed output of a set. The test passes on one machine and fails on another.
- Assuming a
HashMapin Java returns keys in insertion order because it did so in a small example. - Using the first item you get from a set as "the smallest" or "the oldest".
- Modifying a dict while looping over it. Python raises
RuntimeError: dictionary changed size during iteration. Loop overlist(d)if you need to delete entries.
Do not use the empty block above. The diagram below shows the decision.
Rule of thumb
Write code as if order does not exist unless the type documents it. When the order matters for output, tests or reproducible results, make it explicit with an ordered type or with sorted.
Exercise
You build seen = {"x", "y", "z"} in Python and print it with a loop. A teammate's test expects the output x y z. Why is this test fragile, and how do you fix it?
Show answer
Set iteration order is not guaranteed, and string hashes are randomized per process, so the order can change between runs. Fix the test by comparing against sorted(seen) or by comparing sets for equality. If insertion order is part of the requirement, store the values as dict keys instead.