How is memory handled in Python's Lists?

56 Views Asked by At

See the code below, as you see when a=[1,2] that is a homogeneous type the address of 1st and 2nd elements differed by 32 bits but in second case when a=[1,'a',3],there is no relation between address of 1st and 2nd element but there is relation between 1st and 3rd element that is address differs by 64 bits. So I want to know how is memory handled and how indexing takes place and how is it linked to being non hashable (that is mutable)

>>> a=[1,2]
>>> print(id(a[0]))
4318513456
>>> print(id(a[1]))
4318513488
>>> a=[1,'a',3]
>>> print(id(a[0]))
4318513456
>>> print(id(a[1]))
4319642992
>>> print(id(a[2]))
4318513520
>>>
1

There are 1 best solutions below

0
AKX On

In general, ids don't matter. Don't worry about ids. Don't look at ids. In fact, it's a CPython implementation detail that ids are memory addresses, because it's convenient. Another Python implementation might do something else.

In any case, you're seeing CPython's small integer cache (see e.g. this question), where certain integer objects are preallocated as "singleton" objects since they're expected to be used often. However, that too is an implementation detail.

The string 'a', on the other hand, is not cached (it might have been interned if your code had been loaded from a .py file on disk), so it's allocated from somewhere else.

As for your question about indexing, CPython (again, another implementation might do things differently) lists are, under the hood, arrays of pointers to PyObjects, so it's just an O(1) operation.