Newbie here. Say I do the following:
a = "123"
b = a[1]
a = "abc"
My understanding is that:
a
is not a string object. "123" is a string object (not sure I'm using "object" word correctly - maybe just "piece of data" or string) created by the first statement to which the namea
is assigned.- Since it is a string, "123" is immutable.
b
is a new name that points to a portion of the "123" object (the digit - which is also a string - "2").b
does not refer to a new piece of data copied from "123". it refers to the same "2" as the one referred to bya[1]
.- the third statement changes the assignment of the name
a
to a brand new, immutable string. the old string is not changed. in any way whatsoever. only the namea
has been changed. - python is automatically garbage collected, which means it frees up memory as data is no longer needed.
See here and here for previous SO discussion about Python's memory model and variables.
So now assuming the above is correct I have a couple questions about this situation:
Since the data that was referred to by
a[0]
anda[2]
is no longer needed after line 3, is it a candidate and/or likely to be garbage collected? Or, sinceb
is still referring to a portion of "123", is the entire string preserved until no names are pointing to any piece it?I'm wondering about this because if for example you have a very large list object, and the only remaining names pointing to it use only a small portion of it and no names point to the entire thing, it seems like this could become a big problem for memory management.
If the string does exist in memory until there are no names pointing to any part of it, is there some way to get back at other parts of the string once there are no names for it? In the example above: once
a
has been reassigned to a new string, andb
is pointing to "2", is there a way to get back the "1" and the "3"?I am not asking because I actually want to do this, it's just a learning exercise.