Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the id of a list change even if the list is moved in memory?

As I know, dynamic arrays (list in Python) move in memory when its size reaches its capacity. And as far as I know the id of an object corresponds to its memory address.

But when appending values to a list many times, its id doesn't change (so it stays in the same place in memory).

Why?

a = []

print(id(a))  # 2539296050560

for i in range(1_000_000):
    a.append(i)

print(id(a))  # 2539296050560
like image 742
Dimka Avatar asked Nov 16 '25 09:11

Dimka


1 Answers

You are making a confusion between the address of the list (what is the id in CPython) and the address of the data. Under the hood and in CPython, a list is an object that contains a pointer to the beginning of its data. So when you extend the list, the data will be moved in memory but the list object will not, allowing it to keep a fix id - which is required per the language.

like image 58
Serge Ballesta Avatar answered Nov 18 '25 22:11

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!