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
CodePudding user response:
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.