Can someone please clarify why the study material says that strings are immutable, however, the language allows us to add characters to the end of a string as such:
In your code, you don’t change an existing string - you create a new instance on each iteration and just use the same variable to store it. You cannot change the contents of a
word without creating a new string and assigning it to a variable. But, for example,
list is mutable because you can change its elements without assignment -
str is immutable, while
list can be changed in Python.
I think I understood.
By word += “!” I’m re-creating the string, word = word + “!”. I am not changing the string in the variable word, but creating a new variable with the same name (word) that amounts to the old variable word + “!”.
Am I understanding this correctly?
The variable is not new. It is simply assigned a new string value. Otherwise your understanding is correct. We’re not changing the string, but replacing it.