Are strings actually immutable?

I just want to comment that the lesson starts off by saying that strings are immutable, but then the solution to section 12 review involves changing a string by successively adding characters to it. That doesn’t sound very immutable to me!

Isaac, the definition of “same” or “different” has to do with the identity of an object. When a Python object is created, it resides in a certain memory address, and that address is its identity. If I claim that the object is mutable, I say that the object at that address can be changed. If immutable, it cannot be changed.

Every time you “change” a string by adding or substituting characters, you are actually creating a new string. It may well be that you assign that new string to the variable name that you were previously using, but it is a new string , i.e., a different object, residing in a different memory location, nonetheless.

By contrast, when you append an element to a list, the resulting list occupies the same memory address as the first.

(The function id() gives you an object identification (the actual memory address in the most common Python implementation)).

my_str = 'abc'
print(my_str, id(my_str))
my_str += "x"      #  same as my_str = my_str + "x". The variable name is reassigned here.
print(my_str, id(my_str))
print()
my_lst = [1,2,3]
print(my_lst, id(my_lst))
my_lst.append("x")    # "mutating" the list
print(my_lst, id(my_lst))

Output:

abc 59852000
abcx 59853792     # same variable name, different string value, different object id 

[1, 2, 3] 56919744
[1, 2, 3, 'x'] 56919744   # same variable name, different list elements, same object id 
1 Like

Patrick, thanks for taking the time to detail how this works behind the scenes.
I hope CodeAcademy amend this bit of the course to avoid confusion, either by making explicit what you have said, or just removing the existing reference to the immutability of strings

I wish they would make these things more explicit, also, Isaac, but Codecademy is apparently commited, in Python, at least, to an instruction style that strongly resists looking “beneath the hood” at the way things work.

That said, one must come to terms early on with mutability vs immutability, one way or another.