Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

Tuple immutability

Tuple immutability

Explanation

Tuples are immutable - we cannot change, add, or remove elements after creation:

my_tuple = (1, 2, 3)
my_tuple[0] = 10  # TypeError: 'tuple' object does not support item assignment

However, there's a subtlety: if a tuple contains a mutable object (like a list), we can still modify that object's contents:

mixed_tuple = (1, [2, 3], 4)

# Can't replace the list with something else:
mixed_tuple[1] = [5, 6]  # TypeError

# But CAN modify the list's contents:
mixed_tuple[1].append(5)
print(mixed_tuple)  # Output: (1, [2, 3, 5], 4)

The tuple itself hasn't changed - it still holds the same list object. We've just modified what's inside that list.

This subtlety can cause bugs if we expect "immutable" to mean the data can never change. Mutable elements inside tuples can still be modified.

What immutability really means

Info

Tuple immutability means we cannot:

  • Reassign elements (e.g., my_tuple[0] = 10)
  • Add or remove elements

But if an element is itself mutable (like a list), its contents can still change.

Verifying with memory addresses

Details

Practice questions

4 questions

In the Python Editor there is code which creates a tuple which contains a list. The code also prints the memory locations of the individual elements within the tuple as well as of the tuple itself.

Modify the list using .append().

Investigate what happens to the memory locations after this change. Choose an option below.

Select the correct answer:

+ 3 more questions