Search code examples
pythonlistdequedel

Will del a[0] in Python copy the whole list?


I am trying to use a simple list with del a[0] to mimic the deque.popleft(). Just want to understand how does del in Python work. For example:

a = [0,1,2,3,4,5]

a is in a continuous space in memory. After I call del a[0], will Python allocate new space and copy 1,2,3,4,5 there, or it will just give a a new address (which is same as a = a[1:]).

If it allocates new space, does it mean del a[0] is a _O (len (a) _ operation?

If del a[0] is the same as a = a[1:], will Python reclaim the memory space that has been deleted from the array?


Solution

  • See this answer: How is Python's List Implemented?

    Python lists are essentially arrays of pointers. So while deletion from the front shuffles the all elements in the entire list into a new position within the same memory space, the entire list is much smaller than what you'd expect if each element were actually stored in the list, and so the shuffle is much faster, in terms of constant time cost.

    But for sure, del a[0] is a O(len(a)) operation, which is why deque exists.

    In terms of memory reallocation, interestingly an element deletion doesn't necessarily mean that element's memory space is immediately deallocated. Lists will increase/reduce in size at certain thresholds to make memory allocation requests more efficient, as well as optimizing against memory fragmentation.

    Edit: This blog post explains in more details

    Clarification: Previously the post did not explain that the memory location of the whole list was the same, but each element was shuffled and possibly some memory is deallocated.