I was curios if could see memory address of lists, arrays and strings in python ans came across something interesting and weird. Can someone explain what is going on ?
>>> l = [1,1,2,2,3,3]
>>> for i in range(6):
... adr = str( id(l[i]) )
... print(f'{l[i]}: {adr[-6:]}')
...
1: 422400
1: 422400
2: 422432
2: 422432
3: 422464
3: 422464
>>>
You can clearly see that elements with same value would in the same memory address accoring to id documentation:
CPython implementation detail: This is the address of the object in memory.
This happens with strings too The second weird thing happened with numpy arrays and i dont know if this happens to lists and strings.
>>> arr
array([1, 2, 3, 4])
>>> id(arr)
140318415946496
>>> id(arr[0])
140318415101680
>>> id(arr[1])
140318415101680
>>> id(arr)
140318415946496
>>> id(arr[0])
140318415101904
>>> id(arr[1])
140318415101904
>>> id(arr)
140318415946496
>>> id(arr[0])
140318415101680
>>> id(arr[1])
140318415101680
>>>
Whenever i call id for the address of arr, the address of arr[0] changes.
Running this on python 3.8.0