liveBook · Manning

Immutable collection

As explained in Python How-To

Immutability is the property of a data structure or object whose contents cannot be changed after creation.

Need to store task metadata that should not change? Use a tuple for fixed values such as creation time and user, and a list for tasks you expect to add or remove. A tuple makes the intention visible and prevents reassignment of its items. It also uses less memory than a list holding the same data. section 3.1.1

A tuple rejects updates

metadata = ("Monday", "Alex") metadata[0] = "Tuesday" # TypeError: 'tuple' object does not support item assignment A tuple also has no append method; calling one raises AttributeError. Choose a list instead when updates are part of the job. section 3.1.1

The protection applies to the tuple’s items, not necessarily to objects inside it. If an item is a list, you can still change that list: section 3.1.3

An inner list can still change

numbers = ([1, 2], [1, 2]) numbers[0].append(3) # numbers is now ([1, 2, 3], [1, 2]) The tuple still refers to the same inner list. Use the distinction when deciding whether a container really protects the data you care about. section 3.1.3

Immutability also matters for hashing: changing an object’s contents conflicts with the expectation of a consistent hash value. Lists, dictionaries, and sets are unhashable; hashability can be checked with collections.abc.Hashable. For record-like data, named tuples are immutable, while ordinary data classes are mutable. Set @dataclass(frozen=True) when a data class’s fields should resist reassignment. section 3.5.2 section 9.2.3

How Python How-To covers it

How deep it goes
Explains rejected tuple updates and the limit posed by mutable inner objects; also shows frozen data-class fields.
Examples
Uses fixed task metadata, failed tuple assignments, mutation of a list inside a tuple, and a frozen data-class assignment error.
What it assumes
Assumes basic Python list use and introduces tuple immutability through attempted updates.
What you can do after
Practice/perform it by choosing tuples for fixed data, lists for changing data, and frozen data classes for fields that should not change.
How it connects
Connects immutable collections to mutability, hashability, named tuples, frozen data classes, and shallow versus deep copying.

Also explained in

Compare how 24 books explain immutable collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.