How to empty a list?

DrFalk3n picture DrFalk3n · Sep 9, 2009 · Viewed 479.8k times · Source

It seems so "dirty" emptying a list in this way:

while len(alist) > 0 : alist.pop()

Does a clear way exist to do that?

Answer

fortran picture fortran · Sep 9, 2009

This actually removes the contents from the list, but doesn't replace the old label with a new empty list:

del lst[:]

Here's an example:

lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

For the sake of completeness, the slice assignment has the same effect:

lst[:] = []

It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).

Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.