4

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Xing Shi
  • 2,152
  • 3
  • 21
  • 32
  • "a is in a continuous space in memory." - doesn't make much sense in Python terms. – Niklas R Jan 08 '15 at 13:31
  • @NiklasR: Well actually in CPython you look under the hood and you find good old pointers and mallocs running around as happily as ever... – zehnpaard Jan 08 '15 at 17:02

1 Answers1

5

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.

Community
  • 1
  • 1
zehnpaard
  • 6,003
  • 2
  • 25
  • 40