Friday, May 6, 2011

Clearing Python lists

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) ]
From stackoverflow
  • 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[:] = []
    
    : Good point, thanks!
    Renato Besen : You have a good point
    musicfreak : Hmm, you learn something new every day.
  • It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.

    This may be useful for large lists, but for small list it should be negligible.

    Edit: As Algorias, it doesn't matter.

    Note that

    del old_list[ 0:len(old_list) ]
    

    is equivalent to

    del old_list[:]
    
    Algorias : gc is not run in cycles. The list is freed as soon as its last reference is dropped.
  • 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
    
  • You could also do:

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

0 comments:

Post a Comment