3

If the list is implemented as a dynamic array, every time the allocated size is completely occupied if the new space is created for the array, why is the id not changing?

>>> a=[]

>>> id(a)
4395087184

>>> for i in range(1000):
     a.append(i)


>>> id(a)
4395087184
2
  • Because Python's lists are mutable. You can change their contents without changing their identity. Commented Nov 7, 2019 at 16:28
  • Isn't the id address of the object? If so, is the memory of the dynamic array not continuous? Commented Nov 7, 2019 at 16:39

1 Answer 1

3

The id of an object is guaranteed to be persistent for the lifetime of the object. So it would violate the specification of the id function if this list's id changed, and you only created one list so there aren't two list objects with different ids.

The way this works in practice is that the list object itself stays in the same memory location, but it holds a (private) reference to the backing array. When the array's capacity needs to change, a new backing array is created and the contents are copied across. The list object's (private) reference is updated to point at the new backing array, but the list object itself hasn't been relocated in memory.

I have written a longer explanation of how this works, including an interactive example which shows box-and-pointer diagrams of the list object and the backing array. You may find this helpful to understand what is actually happening in memory when the backing array is resized.

Sign up to request clarification or add additional context in comments.

2 Comments

Looks like what you are saying about private reference is ob_item in CPython implementation?
Yes, seems like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.