My understanding was that Python strings are immutable.
I tried the following code:
a = "Dog"
b = "eats"
c = "treats"
print a, b, c
# Dog eats treats
print a + " " + b + " " + c
# Dog eats treats
print a
# Dog
a = a + " " + b + " " + c
print a
# Dog eats treats
# !!!
Shouldn't Python have prevented the assignment? I am probably missing something.
Any idea?
Adding a bit more to above-mentioned answers.
id
of a variable changes upon reassignment.Which means that we have mutated the variable
a
to point to a new string. Now there exist twostring
(str) objects:'initial_string'
withid
= 139982120425648and
'new_string'
withid
= 139982120425776Consider the below code:
Now,
b
points to the'initial_string'
and has the sameid
asa
had before reassignment.Thus, the
'intial_string'
has not been mutated.The string objects themselves are immutable.
The variable,
a
, which points to the string, is mutable.Consider:
>>> a = 'dogs'
>>> a.replace('dogs', 'dogs eat treats')
'dogs eat treats'
>>> print a
'dogs'
Immutable, isn't it?!
The variable change part has already been discussed.
Python string objects are immutable. Example:
In this example we can see that when we assign different value in a it doesn't modify.A new object is created.
And it can't be modified. Example:
A error occurs.
'mutable' means that we can change the content of the string, 'immutable' means that we can't add an extra string.
Variables can point to anywhere they want.. An error will be thrown if you do the following: