The code you submitted creates new lines as intermediate objects. These created lines end up with the same content as your originals. In the interim period of time, they do not exactly correspond to the original and should be stored at a specific address.
>>> id('cat') 5181152
As others have answered, by issuing these instructions, you invoke the Python virtual machine to create a string object containing the string "cat". This string object is cached and located at 5181152.
>>> a = 'cat' >>> id(a) 5181152
Again, a was assigned to reference this cached string object at 5181152 containing "cat".
>>> a = a[0:2] >>> id(a) 27731511
At this point, in my modified version of your program, you created two small string objects: 'cat' and 'ca' . 'cat' still exists in the cache. The string to which a refers is a different and possibly new string object containing the characters 'ca' .
>>> a = a + 't' >>> id(a) 39964224
Now you have created another new string object. This object is a concatenation of the string 'ca' at the address 27731511 and the string 't' . This concatenation matches the previous cached string 'cat' . Python does not automatically detect this case. As stated above, you can force a search using the intern() method.
I hope this explanation highlights the steps that address a changed.
There was no intermediate state in your code with a string assigned to 'ca' . The answer is still applicable as the Python interpreter generates a new string object to hold the intermediate result a[0:2] , assigning this intermediate result to a variable or not.
Heath Hunnicutt Aug 04 '11 at 18:24 2011-08-04 18:24
source share