The Question :
361 people think this question is useful
It seems so “dirty” emptying a list in this way:
while len(alist) > 0 : alist.pop()
Does a clear way exist to do that?
The Question Comments :
The Answer 1
577 people think this answer is useful
This actually removes the contents from the list, but doesn’t replace the old label with a new empty list:
Here’s an example:
lst1 = [1, 2, 3]
lst2 = lst1
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.
The Answer 2
185 people think this answer is useful
If you’re running Python 3.3 or better, you can use the
clear() method of
list, which is parallel to
deque and other mutable container types:
alist.clear() # removes all items from alist (equivalent to del alist[:])
As per the linked documentation page, the same can also be achieved with
alist *= 0.
To sum up, there are four equivalent ways to clear a list in-place (quite contrary to the Zen of Python!):
alist.clear() # Python 3.3+
alist[:] = 
alist *= 0
The Answer 3
62 people think this answer is useful
You could try:
alist[:] = 
Which means: Splice in the list
 (0 elements) at the location
[:] (all indexes from start to finish)
The [:] is the slice operator. See this question for more information.
The Answer 4
32 people think this answer is useful
it turns out that with python 2.5.2,
del l[:] is slightly slower than
l[:] =  by 1.1 usec.
$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = "
10000 loops, best of 3: 28.7 usec per loop
$ python -V
The Answer 5
5 people think this answer is useful
lst *= 0
has the same effect as
lst[:] = 
It’s a little simpler and maybe easier to remember. Other than that there’s not much to say
The efficiency seems to be about the same
The Answer 6
-1 people think this answer is useful
list = 
list to an empty list.
Note that you generally should not shadow reserved function names, such as
list, which is the constructor for a list object — you could use
list_ instead, for instance.
The Answer 7
-3 people think this answer is useful
Another simple code you could use (depending on your situation) is:
You have to start index at the length of the list and go backwards versus index at 0, forwards because that would end you up with index equal to the length of the list with it only being cut in half.
Also, be sure that the while line has a “greater than or equal to” sign. Omitting it will leave you with list remaining.