Understanding memory location of Python variables
Bart
bc at freeuk.com
Sun Jun 17 06:01:41 EDT 2018
On 17/06/2018 03:28, Grant Edwards wrote:
> On 2018-06-16, ip.bcrs at gmail.com <ip.bcrs at gmail.com> wrote:
>
>> 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
>
> What's happening is that you're paying attention to the values
> returned by id(), when you should not. The fact that CPython returns
> a VM address when you call id() is just an "accident" of that
> particular implimentation. You shouldn't assume that id() returns
> anything other than a number that is unique to each object. Any time
> you spend worrying about how that number is calculated is proably
> wasted.
>
>> I expected myName[0] to be located at the same memory location as the myName variable itself.
>
> Python is not C.
>
>> I also expected myName[1] to be located immediately after myName[0].
>
> Python is not C.
>
> Just in case you missed that...
>
> Python is not C.
>
So, how /do/ you obtain the memory address of those values are located?
For example, in order to pass it to some foreign C function that takes a
void* parameter.
I assume there is a memory address at least for the "Kevin" value, as
the other two might yield temporary objects for "K" and "e" rather the
in-place strings which are the first and second characters of the name.
--
bart
More information about the Python-list
mailing list