Understanding memory location of Python variables

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jun 16 19:34:22 EDT 2018


On Sat, 16 Jun 2018 09:38:07 -0700, ip.bcrs 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.

Nothing in the above example tells you anything about memory locations 
(except by accident).

The id() function does not return a memory address (except by accident). 
It returns an opaque integer ID code, that is all. If you try that on 
another Python interpreter, such as Jython or IronPython, you will see 
something like this:

>>> sys.executable
'/usr/bin/jython'
>>> myName = "Kevin"
>>> id(myName)
3
>>> id(myName[1])
4
>>> id(myName[0])
5


Notice that IDs are allocated sequentially, in the order you ask for them.


> I also expected myName[1] to be located immediately after myName[0].

Why? Even if id() happens to return a memory address, the details of 
where Python allocates a new object is unpredictable.


-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list