[Beginner] delete items of [] also from memory

Eric Brunel eric_brunel at despammed.com
Mon Nov 22 14:19:54 CET 2004

Birgit Rahm wrote:
>> But...  And if you try ?
> I tryed A = [].
> And  I think thats why my RAM is filling up. But I dont know if this is the
> problem. So I asked.
> Is del A[0:] the better or an equal solution?
> Birgit

Not exactly equal, but it depends on the context. Consider:

a = [None] * 10000
b = a
a = []

The first line creates a 10000 element list and adds a reference to it ("a"); 
the second adds a new reference to the list ("b"); the third removes a reference 
from the list and makes it point to a new empty list. So the 10000 element list 
still has a reference ("b"), and is not deleted from memory, since it can still 
be accessed via the variable b.

OTOH, consider this:

a = [None] * 10000
b = a
del a[:]

The two first lines are the same, but the third one does not just delete a 
reference to the 10000 element list; it actually deletes all elements from the 
list itself. So now, a *and* b point on the empty list, and the memory used by 
the original list is given back to the system (or should be... see further)

What makes you think the memory is not given back to the system? Does the memory 
occupied by your script increase and increase, or do you just see the memory 
occupied by your script remain constant when you do the del a[:]? In the latter 
case, it may be perfectly normal: it is quite frequent that the memory freed by 
an operation is not returned immediatly to the system, but kept for future use 
by the program.

BTW, I tried the following script, watching the memory consumption at each line:

 >>> a = [None] * 10000
 >>> a = []
 >>> b = [None] * 10000
 >>> b = []
 >>> c = [None] * 10000
 >>> c = []
 >>> d = [None] * 100000

The first line actually increase the memory allocated for the Python 
interpreter; the second one doesn't decrease it, but the third one does not 
increase it, because the memory occupied by the first 10000 element list was 
re-used for the second one. Same thing for the third 10000 element list (the one 
put in c). The last line *did* increase the consumed memory, because more space 
was needed for the 100000 element list.

- Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com

More information about the Python-list mailing list