A lesson from Python Done Right
£29/month
£29/month£29/month or £249/year · 30-day money-back guarantee
Get full accessOur content is best on a larger screen
Tuple immutability
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.
Info
Tuple immutability means we cannot:
my_tuple[0] = 10)But if an element is itself mutable (like a list), its contents can still change.
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 · unlocked with a subscription
Every time you pull an answer from memory, the memory gets stronger. Reading doesn't do that. Nodeledge asks you questions on every step of every lesson, then asks again after days, weeks and months.