Tip:
Highlight text to annotate it
X
So far I've told you that mutation
modifies the existing object.
But you can't really see the difference from what we've done with strings.
Where we'll really see the difference is when we introduce a new variable.
Let's go back to the example we had before,
and now we're going to add an extra assignment statement,
and we'll introduce a new variable.
Suppose we introduce the variable "q."
And we assign p to q, and that means the value of p,
which is the object that's this list,
is now what q will refer to.
The important thing here is after the assignment,
p and q refer to the same list.
Suppose we did an assignment statement
to modify the value of one of the elements of q.
Well, that will change element 4 of q,
so this is element 4 of q.
It will change that value
to the new exclamation point.
It also changed the value of p.
Even though the assignment statement didn't include p,
the fact that p and q refer to the same object
means that it changed the value of p.
To show you that things are different with strings,
let's try that with a string.
See if you can guess what happens when we try to use assignment
to replace the first letter in the string.
Let's run it to see what happens.
And what we get is an error,
and we get an error because the string is not mutable.
There's no way to change the value of the string,
and the error says there's no way to do assignment in a string,
that that type of object, because it's immutable, does not support assignment.
A key difference between mutable objects and immutable objects
is once an object is mutable,
then we have to worry about other variables that might refer to the same object.
We can change the value of that object,
and it affects not just the variable that we think we changed,
it affects the value of other variables as well.
Let's see an example of that.
I've initialized p to the list containing the strings "Hello."
Now I have an assignment that introduces the new variable q
and assigns p to that variable.
And we'll print out the values of p and q,
and we'll see that both p and q contain the string Hello.
But now let's change the value at position 0.
Now we have an assignment that stores
in the value at position 0 of p the letter y.
This changes the value of p.
What may be more surprising is this also changes the value of q.
Even though we didn't use q in the assignment,
it changed the value of q because q
refers to the same object as p.