How can I empty the contents of a list?


#1

Question

If I have a list containing items, how can I empty or delete all the contents of the list?

Answer

There are two ways to empty an existing list. The first way is to just assign the list variable to an empty list. In this case, the old list and its contents are automatically deleted by Python. This is shown in the following code example.

list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
list1 = []

The second method is to use the del() function to delete all the elements of the list. This forces the removal of all the items immediately instead of letting Python delete the contents at some time of its choosing. Both methods produce the same end result which is that the list will be empty of contents.

list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
del list2[:]

#2

In the second example above it is important to include the slice subscript, else the variable itself will be deleted.

>>> list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
>>> del list2[:]
>>> list2
[]
>>> isinstance(list2, list)
True
>>> list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
>>> del list2
>>> isinstance(list2, list)
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    isinstance(list2, list)
NameError: name 'list2' is not defined
>>> 

Clearly, the first example is the preferred approach, assign an empty list, since it is not likely to ever throw a wrench into the proceedings (a bug that could be tricky to find).