liveBook · Manning

Mutation

As explained in Get Programming: Learn to code with Python

Mutation is a change to an existing value, object, data structure, state, or representation.

Mutation changes an existing object directly. With a Python list, adding, removing, or changing elements alters the list itself; you do not need to assign the result to another variable. section 25.7 section 26.0

List operations can mutate a list in different ways:

  • append adds one element at the end; insert adds one at a chosen index. section 25.4
  • extend adds another list’s elements in order, leaving that other list unchanged. section 25.4
  • If multiple variables refer to the same mutable object, changing it through one variable is visible through the others. section 28.3
Listing 25.2. Adding items to a list
first3letters = []                       #1
first3letters.append("a")                #2
first3letters.append("c")                #3
first3letters.insert(1,"b")              #4
print(first3letters)                     #5
last3letters = ["x", "y", "z"]           #6
first3letters.extend(last3letters)       #7
print(first3letters)                     #8
last3letters.extend(first3letters)       #9
print(last3letters)                      #10

Follow how append, insert, and extend change lists, then compare the resulting lists. section 25.4

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through append, insert, and extend, and notes shared changes through aliases.
Examples
Uses grocery lists and code that appends, inserts, and extends list elements.
What it assumes
Builds from basic Python lists and explains that list operations directly change them.
What you can do after
Apply append, insert, and extend to change lists, and recognize changes shared through aliases.
How it connects
Connects mutation to Python lists, mutable objects, aliasing, and copying.

Also explained in

Compare how 12 books explain mutation →

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.