Skip to the page

Core data model · core

Mutable and immutable types, and what can be a dict key

A name points to an object. Some objects can change in place (list, dict, set) and some cannot (int, str, tuple). Dict keys must be hashable, so a list cannot be a key and a tuple can only if everything inside it is hashable.

The notes

What you must know

  • Mutable: list, dict, set, bytearray and most user classes. Immutable: int, float, bool, str, bytes, tuple, frozenset, None.
  • Dict keys and set members must be hashable, and the hash must not change while the object is inside. A list gives TypeError: unhashable type: 'list'.
  • A tuple is hashable only if all its items are hashable. ([1], 2) cannot be a key.
  • A tuple fixes which objects it holds, not what is inside them. t[1] += ["y"] on ("a", ["x"]) extends the list in place, then fails when it assigns back, so the tuple shows the change and also raises TypeError.
  • += on a list changes it in place (iadd); on a str or a tuple it makes a new object.
  • True == 1 == 1.0 and they have equal hashes, so {True: "a", 1: "b", 1.0: "c"} has one key. The dict keeps the first key object and the last value.
  • To use your own class as a key, define eq and hash from immutable fields, or use @dataclass(frozen=True).

The red pen

Common traps: mistake → fix

  • Mistake: Tuples are always hashable

    Fix: only when every item inside is hashable.

  • Mistake: Python passes ints by value and lists by reference

    Fix: Python passes references to objects ("call by sharing"); mutating an argument changes the caller's object, rebinding the name does not.

  • Mistake: An immutable tuple cannot change, so the failed t[1] += ["y"] left it untouched

    Fix: the list inside was already extended before the error.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which built-in types are mutable and which are immutable?
  2. Can a list be a dictionary key? Can a tuple?
  3. Why can ([1], 2) not be a dict key, although a tuple is immutable?
  4. What does t[1] += ["y"] do when t = ("a", ["x"])? Does it raise, and does t change?
  5. How would you make your own class usable as a dict key?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview