Course contentsShow
← Python
Lesson 208 of 1,0604. Data Structures MasteryFree lesson

Comparing Reference Semantics in Mutable and Immutable Sequences

Learners will distinguish between modifying a list in-place and creating new objects when performing operations on immutable tuple sequences.

Comparing Reference Semantics in Mutable and Immutable Sequences

In this lesson, you will learn how the choice between lists and tuples fundamentally changes whether Python modifies existing data or creates new objects in memory.

The Mutable Approach: Modifying In-Place

When you work with a list, you are dealing with a mutable container. Because lists are designed to be changed, operations like append() or item assignment modify the object directly at its memory address. This means that if two variables point to the same list, a change made through one variable is reflected in the other:

original = [1, 2, 3]
reference = original
original.append(4)

print(reference)  # Output: [1, 2, 3, 4]

The variable reference sees the update because both names point to the exact same memory block. The list object itself was "mutated" in place.

The Immutable Approach: Creating New Instances

In contrast, tuple objects are immutable. They cannot be changed once created. If you perform an operation that appears to modify a tuple—such as concatenation—Python does not change the original object. Instead, it creates an entirely new tuple object and assigns it to your variable.

tuple_a = (1, 2, 3)
tuple_b = tuple_a
tuple_a = tuple_a + (4,)

print(tuple_b)  # Output: (1, 2, 3)
print(tuple_a)  # Output: (1, 2, 3, 4)

Notice that tuple_b remained unchanged. When we used the + operator, Python created a new memory location for the result and updated the name tuple_a to point to this new object. The original data remained preserved in its own separate memory slot.

Understanding this difference is vital for writing bug-free code. When using lists, you must be cautious of "side effects" where changing data in one place unexpectedly impacts other parts of your program. With tuples, you gain the safety of knowing your data cannot be altered by other parts of your code, as any "modification" results in a fresh copy.

Key Takeaway: Mutable sequences (lists) allow for in-place modifications that affect all references to the object, while immutable sequences (tuples) force the creation of new objects, ensuring the original data remains protected.