[Tutor] string immutability

Dave Angel d at davea.name
Mon Oct 24 20:45:10 CEST 2011

On 10/24/2011 02:04 PM, Johan Martinez wrote:
> Hi,
> I am struggling to understand Python string immutability. I am able to
> modify Python string object after initializing/assigning it a value. So how
> does immutability work? I am not following it. Sorry for really stupid
> question. Any help?
You're confusing attributes and objects.  When you say  s = "First"  two 
distinct things happen.  An immutable object of type str is created, 
with an immutable value "First".  And then the attribute s is bound to 
that object.  s is not immutable at all.

Then when you do  s = "Second" you are creating a totally different 
immutable object, which s is now bound to. And behind the scenes, the 
first object is garbage collected.

We all confuse this by referring to "variables," but they are not the 
same as "variables" in most other languages.  They never have a value, 
they just refer to an object.  And if you do    t = s, you're not 
copying a value at all.  You're just saying that t and s now are bound 
to (refer to) the same object.  If the object is immutable, then you 
don't need the distinction.  But if you mute the object, as opposed to 
creating a new one, both the attributes are still bound to the same object.

Top-level  (global) variables are attributes of the module.  Local 
variables are attributes of the function.  And instance variables (an 
incorrect term) are attributes of an instance, frequently referred to 
as    obj.inst

Going from the other end, an object may be bound to one place, two 
places, or many.  And when it's bound to nothing, it gets garbage 
collected (sometimes ref-counted, but that disctinction refers to a 
particular implementation, not to the language Python).  Those "places" 
I'm referring to may be attributes, so we see it as having "a name", but 
it may be bound to something without an explicit name, such as an 
element of a list.

Ints, floats, and strings are immutable.  So I guess the simplest object 
that's mutable is a list.  You can modify the 3rd item in a list without 
affecting any of the "variables" that are bound to it.  But when you use 
any of those variables, it'll appear to have a "new value."

list1 = [3, 0, 44]
list2= list1
list3 = [10, 12, 15, 22]

list1[2] = 45       #mutates the list object bound to list1
       #but list2 is bound to the same object
print list2  #will now be [3, 0, 45]

list2 = list3   #doesn't mutate any objects, it simply rebinds list2 
from the first list object to the second one.




More information about the Tutor mailing list