Hashability

Dicts and sets find keys fast by computing hash(key), a number that says where to look. That only works if a key's hash never changes. So keys must be hashable, which in practice means immutable.

  • Strings, numbers, None, tuples and frozensets are hashable.
  • Lists, dicts and sets are not. Using one as a key raises a TypeError that says "unhashable type".
  • A tuple is hashable only if everything inside it is. (1, [2]) is not.

When you need a list as a key, convert it to a tuple first. Grid positions like (row, col) as dict keys or set items are everywhere in interview problems: visited cells, memo tables, coordinates.

Equal objects must have equal hashes. That's why 1 and 1.0 count as the same key.

Run it, then try {1: "int", 1.0: "float"} and see how many keys you get.