How does Python keep the same memory reference as a list after resizing it?

Asked

Viewed 409 times

2

We know the objects of the type list, because they are based on dynamic vectors, it has a maximum internal capacity. We also know that when this total capacity is reached and we want to insert a new value in the list, Python allocates a new array with a capacity greater than the previous one and transfers all values of the array previous to the new array. But how the language allocates a new portion of memory without losing the reference of the previous one?

lst = []
print(id(lst))

for i in range(999):
    lst.append(i)

print(id(lst))

When executing the code, we can see that the id’s will be the same, even after the resizing operations. How is this possible?

2 answers

3

Because the object of the list is not the direct reference to the array, it is a structure with some information, among them the reference to the array that makes up the list. This is internal language information, it doesn’t matter to the programmer. The object of the list remains the same, but its contents change, hence the id doesn’t change.

One reply in OS shows implementation details (maybe today is slightly different, but it doesn’t change much).

2


The function id() returns a unique identifier of an object instance. When resizing a list, although the object changes in its internal state, the instance remains the same, which makes it id() always return the same identifier.

Follows a curious reference:

x = 1
y = x
x = y
z = 1

print(id(x))  # x referencia o inteiro 1
print(id(y))  # y referencia x
print(id(z))  # z referencia y
print(id(1))  # referencia para o inteiro 1

lst = []
copia = list(lst)
referencia = lst

# Altera somente estado interno da lista
for i in range(999):
    lst.append(i)

print(id(lst))         # id da lista original
print(id(copia))       # copia da lista possui uma instancia/id diferentes
print(id(referencia))  # referencia possui o mesma instancia/id da lista referenciada

Exit:

25037928
25037928
25037928
25037928
139864956135184
139864956180168
139864956135184

Browser other questions tagged

You are not signed in. Login or sign up in order to post.