Explore Immutability in Tuples and Strings
00:00 Another thing that they have in common with strings is that tuples are immutable, which means that you can’t change the value of an element in a tuple after creating it, just like you can’t change a single character in a string once you’ve created the string.
00:14
So if you tried to do an item assignment—for example, here we have the numbers
tuple, and you’re attempting to replace the first element with the integer 2
—then you get an error because this just doesn’t work.
00:28
Let’s try it out live. We still have the numbers
tuple here available. So I’ll try to change the final element [-1]
, and I will try to assign it to the number 100
.
00:45
Just as expected, I get the TypeError
that the tuple
object does not support item assignment. Again, let’s compare it to the string. You’ll get the same.
00:53
So if I wanted to change the first letter of "Python"
to make it say maybe "Tython"
01:03 Python protects itself from something like that—no, it’s just the same reason as with the tuple, is that strings are immutable, so the string object does not support item assignment.
Become a Member to join the conversation.