Search⌘ K
AI Features

Recap: Mutability vs. Immutability

Explore the concepts of mutability and immutability in Python to understand how data changes affect program behavior. This lesson helps you recognize when objects can be modified safely and when copying is necessary to avoid unintended side effects, improving your ability to write predictable and efficient code.

Predictable behavior is essential in software systems. When you modify a variable, you typically expect the change to affect only that reference. In Python, multiple variables can reference the same object. If one reference modifies a mutable object such as a list, the change is visible through all other references to that object. This behavior comes from the distinction between mutable and immutable types. Understanding this distinction helps you reason about when and how data changes in a program.

The immutable standard

To recap, in Python, some objects are immutable, meaning their internal state cannot be changed once they are created. The fundamental types we have used so far, integers, floats, booleans, strings, and tuples, belong to this category.

It is important to distinguish between changing a variable and changing an object. When we update a variable that refers to a number (for example, score = score + 10), we are not modifying the original integer object. Instead, Python creates a new integer object and rebinds the name score to reference it. The original object ...