liveBook · Manning

Immutable collection

As explained in Get Programming: Learn to code with Python

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

An immutable collection cannot be changed after it is created. In Python, a tuple is immutable; a list is mutable. If you need different contents in a tuple, you create another tuple rather than change the original one. section 24.1 section 24.2

A new tuple, not a changed tuple

Start with `groceries = ("milk", "eggs")`. Later, `groceries = ("milk", "eggs", "bread")` gives the name `groceries` a new tuple. It does not add bread to the first tuple. By contrast, a list can add bread to the same object with `append()`. section 24.1 section 24.2

Figure 24.1. The variable named a is bound to an object with value 1 in one memory location. When the variable named a is bound to a different object with value 2, the original object with value 1 is still in memory; you just can’t access it anymore through a variable.

The diagram uses integers rather than collections, but it shows the same important distinction: assigning a new value to a name does not change the immutable object it previously named. section 24.1

Why does the distinction matter? A dictionary uses a key’s value to find its stored value again. Its keys must be immutable so that a key does not change between storing and looking up an item. The dictionary itself can still change, and its values may be mutable or immutable. Quick check: if you assign a new tuple to a name, which tuple changed? Neither. section 27.2 section 27.6

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines immutability and explains variable rebinding through memory diagrams; contrasts it with direct changes to a list.
Examples
Uses a grocery list, memory diagrams, and dictionary key lookups to contrast replacing an object with changing one.
What it assumes
Assumes familiarity with Python variables and basic types, while defining immutable and mutable objects from zero.
What you can do after
Evaluate/understand whether an assignment replaces a collection or modifies it, and why dictionary keys must remain unchanged.
How it connects
Connects tuples to mutable lists, variable binding, dictionary keys, and hash functions.

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 Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.