Mar-01-2019, 01:53 PM
All of these are Python peculiar properties:
Small integers are preallocated in array called
It covers interval from -5 to 256.
So, if
Internal behavior with string is harder to explain. Python preallocates each Python string that contains only ascii-chars and digits (may be some special chars too, i didn't explore this in deep) (see here). So, if you try to do the same with, e.g.
Finally, each time you are creating a list, a new object is created, even if you try to create an empty list:
Small integers are preallocated in array called
small_ints
see CPython implementationIt covers interval from -5 to 256.
So, if
x=500
and y=500
, id(x) == id(y)
will return False
.Internal behavior with string is harder to explain. Python preallocates each Python string that contains only ascii-chars and digits (may be some special chars too, i didn't explore this in deep) (see here). So, if you try to do the same with, e.g.
abc-1
, you will end with False
:x = 'abc-1' y = 'abc-1' id(x) == id(y) # FalseThis is because these strings contains
-
.Finally, each time you are creating a list, a new object is created, even if you try to create an empty list:
x = [] y = [] id(x) == id(y) #FalseSince, -5 to 256 numbers are prealloced objects, you can do some terrible things (using ctypes which allows to get direct access to memory), e.g. let assign to object
5
different value, e.g. 8: import ctypes mnt = id(6) - id(5) # the number of bytes per num ctypes.memmove(id(5), id(8), mnt) # Try to break Python's mind.... (Don't do this) 5 + 3
Output:11