Understanding memory location of Python variables

Peter Pearson pkpearson at nowhere.invalid
Sun Jun 17 18:18:37 EDT 2018


On Sat, 16 Jun 2018 09:38:07 -0700 (PDT), 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

You left out one of the more interesting (and possibly informative)
angles:

>>> myName = "Kevin"
>>> x0 = myName[0]
>>> x1 = myName[1]
>>> x01 = myName[0:2]
>>> y0 = "K"
>>> y1 = "e"
>>> y01 = "Ke"
>>> id(x0) == id(y0)
True
>>> id(x1) == id(y1)
True
>>> id(x01) == id(y01)
False
>>> x01 == y01
True

myName[0] is the string "K", and this Python implementation happens
to economize by having only a single object "K".  This economy measure
probably only applies to single-character strings.

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list