Understanding memory location of Python variables

MRAB python at mrabarnett.plus.com
Sat Jun 16 13:35:18 EDT 2018


On 2018-06-16 17:38, ip.bcrs at gmail.com wrote:
> Hi everyone,
> 
> I'm intrigued by the output of the following code, which was totally contrary to my expectations. Can someone tell me what is happening?
> 
>>>> myName = "Kevin"
>>>> id(myName)
> 47406848
>>>> id(myName[0])
> 36308576
>>>> id(myName[1])
> 2476000
> 
> I expected myName[0] to be located at the same memory location as the myName variable itself. I also expected myName[1] to be located immediately after myName[0].
> 
The 'id' function returns an integer ID for a value/object. The only 
guarantee is that no 2 values have the same ID at the same time.

It is _not_ an address.

myName is bound to the string "Kevin", and id(myName) tells you the ID 
of that string.

myName[0] returns the string "K", and id(myName[0]) tells you the ID of 
that string.

(As a side note, The CPython implementation, which is written in C, 
happens to use the address, but the Jython implementation, which is 
written in Java, doesn't.)



More information about the Python-list mailing list