tags:

views:

1068

answers:

4

Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:

old_list = []
old_list = list()

The reason I ask is that I just saw this in some running code:

del old_list[ 0:len(old_list) ]
+20  A: 

To clear the list in place, so references "see" the same list.

For example, this method doesn't clear the referenced list:

>>> a = [1,2,3]
>>> b = a
>>> a = []
>>> print a
[]
>>> print b
[1, 2, 3]

But this one does:

>>> a = [1,2,3]
>>> b = a
>>> del a[0:len(a)]
>>> print a
[]
>>> print b
[]
>>> a is b
True

You could also do:

>>> a[:] = []
Koba
Good point, thanks!
You have a good point
Renato Besen
Hmm, you learn something new every day.
musicfreak
+1  A: 
Renato Besen
gc is not run in cycles. The list is freed as soon as its last reference is dropped.
Algorias
A: 

There are two cases in which you might want to clear a list:

  1. You want to use the name old_list further in your code;
  2. You want the old list to be garbage collected as soon as possible to free some memory;

In case 1 you just go on with the assigment:

    old_list = []    # or whatever you want it to be equal to

In case 2 the del statement would reduce the reference count to the list object the name old list points at. If the list object is only pointed by the name old_list at, the reference count would be 0, and the object would be freed for garbage collection.

    del old_list
Alex
A: 

You could also do:

while l:
    l.pop()
RoadieRich
LOL. I'm sure that's efficient.
FogleBird
Nobody said anything asbout it being efficient...
RoadieRich
+1 for evillness
Oleksandr Bolotov