[Tutor] How memory works in Python
Mats Wichmann
mats at wichmann.us
Tue Jan 7 10:06:46 EST 2020
On 1/7/20 7:44 AM, Deepak Dixit wrote:
> Hi Team,
>
> I was thinking on the memory management in Python but little confused here
> because when I assign same value of type number and string to different
> variable, it points to same memory but when I do it for list or tuple it
> points to different memory locations.
>
> Here is the code and the output:
>
> # test.py
> x1 = 10
> y1 = 10
>
> x2 = "Hello"
> y2 = "Hello"
>
> x3 = [10]
> y3 = [10]
>
> x4 = (10,)
> y4 = (10,)
>
> print id(x1) == id(y1)
> print id(x2) == id(y2)
> print id(x3) == id(y3)
> print id(x4) == id(y4)
>
> deepak at Deepak-PC:~$ python test.py
> True
> True
> False
> False
>
>
> Can you help me to understand how it works?
quite simply, if works as you expect, but with some optimizations.
Turns out small integers are cached in CPython - they reuse the same
object. The current range of that is something like up to 256 (I think a
small number of negative integers also have this happen). Try that
experiment again with bigger numbers.
Similarly for strings, small strings are interned, try it with a
considerably longer string.
You can cause the string interning to happen yourself with the intern
function, see this example:
>>> y1 = "Hello, this is a much longer string"
>>> y2 = "Hello, this is a much longer string"
>>> print(id(y1) == id(y2))
False
>>> import sys
>>> y1 = sys.intern("Hello, this is a much longer string")
>>> y2 = sys.intern("Hello, this is a much longer string")
>>> print(id(y1) == id(y2))
True
>>>
More information about the Tutor
mailing list