liveBook · Manning

Immutable collection

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

An immutable collection is a collection whose membership and contents cannot be changed after creation.

Immutability is the property of an object or value whose state cannot be modified after creation. Python strings and tuples are immutable: changing them requires creating or assigning a new value. section 8.1 section 22.1.1

In Python, immutability changes how programs update data:

  • Rejects item assignment on strings and tuples instead of changing their contents. section 10.1.4 section 22.1.1
  • Produces a new string through methods such as str.replace(), str.translate(), or string reconstruction. section 8.6 section 8.1.1
  • Contrasts with mutable lists, which can be edited in place and later joined into a string. section 10.3.2
  • Supports tuples and named tuples when data should not be accidentally modified during program execution. section 22.1.2

Rebuild an immutable string

>>> text = 'The quick brown fox.' >>> text[2] = 'i' TypeError: 'str' object does not support item assignment >>> text = text[:2] + 'i' + text[3:] >>> text 'Th i quick brown fox.' For repeated character edits, convert the string to a list, modify the list, and use ''.join(text) to create a new string. section 10.1.4 section 10.3.2

>>> state[1] = 'O'
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Observe the TypeError produced when tuple item assignment attempts to modify an immutable value. section 22.1.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Demonstrates failed assignments, reconstruction, list conversion, and named-tuple safety without examining Python object internals.
Examples
Shows string replacement, random character mutation, shuffled word middles, dictionary keys, and tic-tac-toe state tuples.
What it assumes
Assumes basic Python indexing and assignment while teaching mutable and immutable data types through direct REPL experiments.
What you can do after
Apply immutability by rebuilding strings, converting them to editable lists, or choosing tuples and named tuples for protected state.
How it connects
Connects immutability with strings, lists, tuples, named tuples, dictionaries, slicing, and in-place mutation.

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 Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.