3.5. Mutable and Immutable Sequences¶
We have seen that in many ways lists and strings are similar, but there is a major distinction between these containers. In this section, we introduce the idea for mutable and immutable sequences and reconsider lists, strings and tuples in this light.
3.5.1. Strings and Tuples are Immutable¶
One final thing that makes strings different from lists is that you are not
allowed to modify the individual characters in the collection. It is tempting
to use the []
operator on the left side of an assignment, with the intention
of changing a character in a string. For example, in the following code, we
would like to change the first letter of greeting
.
In [1]: greeting = "Hello, world!"
In [2]: greeting[0] = 'J' # ERROR!
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-fe47087f0508> in <module>()
----> 1 greeting[0] = 'J' # ERROR!
TypeError: 'str' object does not support item assignment
In [3]: greeting