Understanding memory location of Python variables

Chris Angelico rosuav at gmail.com
Sat Jun 16 19:45:22 EDT 2018


On Sun, Jun 17, 2018 at 2:38 AM,  <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].
>

A string or array in C is allocated in contiguous memory. Python,
however, is not C. What you're looking at is the identities of
objects, not the memory locations of bytes. Everything you're assuming
about C should be discarded.

ChrisA



More information about the Python-list mailing list