Python · Module III. Code architecture

Lesson 10a. Mutable and Immutable

Which types are mutable, id(), the b = a trap, .copy() and deepcopy, and why dict/set keys must be immutable.

AdvancedReading ≈ 25 minPractice ≈ 25 minNot started

In short

Which types are mutable, id(), the b = a trap, .copy() and deepcopy, and why dict/set keys must be immutable.

How it works

A Python variable is a name (a label) pointing to an object in memory. A mutable object can change in place; an immutable one cannot — every "change" creates a new object.

  • Immutable: int, float, bool, str, tuple, frozenset, None
  • Mutable: list, dict, set
  • id(x) returns the object's identity number; a is b checks whether it is the same object.

.copy() (or list(a), a[:]) makes a shallow copy: the outer list is new, but inner lists are still shared. For a full copy of a nested structure use copy.deepcopy.

Rule: a dict key and a set element must be immutable (more precisely, hashable). str, int and tuple work; list and dict do not: TypeError: unhashable type: 'list'.

Loading progress…