python 3.8 cpython on windows 10
case 1:
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
print(id('sss'))
output:
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
2343368851504
case 2:
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
print(id([1, 2, 3, 4, 5]))
output:
2343339032320
2343339036864
2343339032512
2343339037568
2343339032320
2343339036864
2343339032512
2343339037568
2343339032320
2343339036864
for case 1:
print the address of an immutable object several times. they are the same without doubt.
for case 2:
print the address of mutable object several times. Each address appears periodically, like every four in a cycle.
so what's the machanism behind it.
chatgpt's answer to it:
for immutable objects like
small integers or interned strings
(as discussed in the previous response), Python may reuse the same object for multiple variables with the same value for optimization purposes. When you assign a certain number of empty lists to different variables, there is a possibility that their memory addresses will repeat in a regular pattern.
In CPython, the default implementation of Python, the memory allocation strategy for small objects, including empty lists, follows a technique called
memory pooling
. The memory pool consists of preallocated fixed-size blocks of memory. When an object is created, Python assigns memory from the available blocks in the pool. For small objects, such as empty lists, Python tries to optimize memory usage by reusing the same memory blocks whenever possible. As a result, if you assign a certain number of empty lists, you may observe a pattern in the memory addresses.
maybe it has nothing to do with id()
method