How does Python maintain the same memory reference of a list after resizing it?

2

We know that objects of type list , because they are based on dynamic vectors, have a maximum internal capacity. We also know that when full capacity is reached and we want to insert a new value into the list, Python allocates a new array with a larger capacity than the previous one and transfers all values from the array to the new array . But how does the language allocate 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?

    
asked by anonymous 10.10.2017 / 17:10

2 answers

2

The function id() returns a unique identifier of the instance of an object. When you resize a list, even though the object undergoes a change in its internal state, the instance remains the same, which causes id() " always returns the same identifier.

Here is 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

Output:

25037928
25037928
25037928
25037928
139864956135184
139864956180168
139864956135184
    
10.10.2017 / 18:41
3

Because the list object is not the direct reference to array , it is a structure with some information, including the reference to the array that makes up the list. This is an internal information of the language, it does not matter to the programmer. The list object remains the same, but its content changes, so id does not change.

A response in the OS shows details of the implementation (maybe today is slightly different but does not change much).

    
10.10.2017 / 17:18