liveBook · Manning

Immutable collection

As explained in Python Workout: 50 ten-minute exercises

A property of an object whose state cannot be changed after the object is created.

Immutability means that an object's state cannot change after creation. In Python, strings are immutable: attempting to assign through an index such as s[0] = '!' raises an exception instead of changing the string. section 2.6

Immutability affects how values are used:

  • Strings, integers, Boolean values, and tuples cannot be modified in place. section 2.6 section 3.0
  • Lists are mutable sequences suited to collections of similar items; tuples are immutable sequences suited to records containing different types. section 3.0
  • Operations on immutable values produce new objects rather than changing the existing value. section 2.6
  • Immutable values can be passed to functions without the function modifying them and shared across threads without locking for changes. section 2.6

Rebinding instead of modifying

s = 'abcd' s[0] = '!' # raises an exception t = s s = '!bcd' The last assignment binds s to a new string; it does not modify the string previously referenced by t. This replacement-oriented style also supports functional programming, which keeps data immutable and transforms inputs into outputs. section 7.0

Table 3.1 Sequence comparison (view table figure)

Type

Mutable?

Contains

Syntax

Retrieval

str

No

One-element strings

s = 'abc'

s[0] # returns 'a'

list

Yes

Any Python type

mylist = [10, 20, 30, 40, 50]

mylist[2] # returns 30

tuple

No

Any Python type

t = (100, 200, 300, 400, 500)

t[3] # returns 400

Compare strings, lists, and tuples by mutability, contents, syntax, and indexed retrieval. section 3.0

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines immutability, demonstrates failed string mutation, and connects it to functions, threads, dictionaries, and functional programming.
Examples
Uses indexed string assignment, rebinding, list-versus-tuple comparisons, and immutable data transformations.
What you can do after
Apply immutable-value reasoning when choosing collections, passing data to functions, and replacing rather than modifying values.
How it connects
Connects immutability with strings, tuples, lists, dictionaries, functions, threads, and functional programming.

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 Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.