On Sun, Jun 17, 2018 at 8:01 PM, Bart <b...@freeuk.com> wrote: > On 17/06/2018 03:28, Grant Edwards wrote: >> >> On 2018-06-16, ip.b...@gmail.com <ip.b...@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.
For strings? You don't. > 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. > You assume wrong. Now, if you're talking about a data type that DOES have a concrete in-memory representation (such as memoryview), then the answer may be different. But in Python, no, you cannot find out where the data is located, because it quite probably isn't stored in any way that would be useful to you. If you're implementing a function *in C* that needs to accept a Python string as a parameter, you can take that string object and say "hey Python, can you give me a UTF-8 buffer with the contents of this string pls thx?", and you'll get one. But that's a conversion - albeit one that may be cached. ChrisA -- https://mail.python.org/mailman/listinfo/python-list