370

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

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

Does a clear way exist to do that?

martineau
  • 119,623
  • 25
  • 170
  • 301
DrFalk3n
  • 4,926
  • 6
  • 31
  • 34
  • 28
    So why do python dicts and sets have a clear() method, but not lists? – job Sep 09 '09 at 16:59
  • 13
    But if there are multiple references to the object, it might be useful. – Ned Deily Sep 09 '09 at 21:05
  • 3
    It might be useful if I need to clear a shared list over processes at run time and don't need to wait for garbaging (or am I wrong? did I misunderstand garbage collection?). Also if I want to check each popped element I can debug it while I can't using slicing (or am I wrong). I don't need to stop process execution while clearing my list. – DrFalk3n Sep 10 '09 at 07:56
  • 2
    @S.Lott Just because you don't understand why this is important doesn't mean the rest of us don't. If multiple objects depend on a common list it will matter. In several design patterns this is important. Garbage collector means you don't have to clean up after yourself; it's not a license to make more of a mess. – UpAndAdam Apr 26 '13 at 22:15
  • 4
    Notwithstanding any other, better answers, your initial code could have been written: while alist: alist.pop() – MrWonderful Nov 24 '14 at 18:54

7 Answers7

586

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.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
fortran
  • 74,053
  • 25
  • 135
  • 175
  • 3
    Two further questions: What is "del" exactly? ( I deduce it del-etes things but I don't really know what is it ) and 2nd: How do you read ( out loud ) [:] – OscarRyz Sep 09 '09 at 16:24
  • 2
    For a sound explanation of del, I'd refer to the docs: http://docs.python.org/reference/simple_stmts.html#the-del-statement – fortran Sep 09 '09 at 16:28
  • 14
    I usually don't read out loud python code xD, but if I had to I think I'd say "slice from the begining to the end of the list l". – fortran Sep 09 '09 at 16:29
  • 2
    @jellybean completely unintended ^_^ English is not my mother tongue, so I really didn't notice the contrast between the two comments. – fortran May 06 '10 at 15:00
  • if we do l = [] won't the old list contents get garbage collected by Python GC ? – Alex Punnen Mar 15 '16 at 12:00
  • @AlexPunnen yes, that is a non issue; thus it wasn't mentioned in the answer – fortran Mar 15 '16 at 18:40
  • Okay OscarRyz, if you start catching variables from a random output loop somewhere into an array that looks like `i=[]`, then each new collected data will be indexed in the array one number higher than the last, starting with 0. But when you first make your array, it's empty. You can of course print it like `print i`, but it will only produce `[]` as output. Also, try being specific: `print i[0]` or `print i[3]`, and you'll get an exception thrown at you. However, as long as **data is stored** in the array, `del i[x]` can be used to clear any one or more of these indexed positions. – Musixauce3000 Apr 05 '16 at 14:11
  • what ever you do do not do a[:] = [] or a = [] on python 3 , its not efficient and its very slow specially if you are iterating and clearing – Serak Shiferaw Mar 27 '19 at 13:10
210

If you're running Python 3.3 or better, you can use the clear() method of list, which is parallel to clear() of dict, set, 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!):

  1. alist.clear() # Python 3.3+
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
62

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.

Community
  • 1
  • 1
Adam Batkin
  • 51,711
  • 9
  • 123
  • 115
  • 6
    Why not just `alist = []`? – mitenka Feb 09 '17 at 18:31
  • 20
    @mitenka that does not empty the list, it overwrites the variable `alist` with a different list which happens to be empty. If anyone else had a reference to the original list, that remains as-is (i.e. it contains whatever was in it to begin with) – Adam Batkin Feb 13 '17 at 03:56
  • @mitenka Another reason is that `alist.clear()` or `alist[:] = []` helps checking that `alist` truly is a list. Say you got `alist` returned from a function `foo()`. You thought `foo` returned a list but indeed it returned a `None`. Using `alist = []` cannot catch that mistake. – aafulei Sep 06 '19 at 02:05
  • I came across this post because I was looking for a way to clear a list or at least I thought that is what I needed to do. I was taking in data and wanted to create sub lists based on a condition and put the sub lists into a master list. Naturally when I would use any of the delete methods it would delete the sub list and the list I was appending in the master list. Mitenka's suggestion was exactly what I needed. Thinking about it, I didn't need to clear the sub list, I needed to reset it back to a new list.. To me it wasn't obvious that is what I needed. Mitenka's suggestion solved my issue. – Thomas Johnson Jun 26 '20 at 23:26
32

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
Python 2.5.2
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • 1
    In Python 2.7.2, on my machine, they're about the same. They both run from 13.5-13.7 usec per loop. – leetNightshade Nov 07 '12 at 22:23
  • You should also measure python3 -mtimeit "l=list(range(1000))" "b=l[:]" to calculate "b[:] = []" and "del b[:]". Do it and lol... – rockdaboot Feb 05 '16 at 10:00
  • 1
    I did the benchmark with python 3.5 and I agree with leetNightshade . `.clear()`, `del b[:]` and `b[:]=[]` all runs the same (`b[:]=[]` being slightly slower. – Conchylicultor Mar 13 '17 at 01:13
6
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

Xantium
  • 11,201
  • 10
  • 62
  • 89
Ivan Hoffmann
  • 149
  • 1
  • 7
  • 1
    For the sake of completeness it's worth mentioning, that any given integer that is less than or equal to `0` would have the same effect. It is a pretty neat trick though, I'm a bit sad, that it didn't receive much attention.. – Peter Varo May 24 '18 at 09:54
-2
list = []

will reset 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 lst or list_ instead, for instance.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 40
    No: this won't modify the list, this just assigns an empty list to the variable `list`. If you expected a function to modify a passed in list (for example), this wouldn't do what you want. – Adam Batkin Sep 09 '09 at 16:12
  • 10
    Not really. The question is "How to empty a list" not "How to assign over a variable that contains a list" – Adam Batkin Sep 09 '09 at 16:17
  • 6
    the question wasn't ambiguous, the op's snippet was popping elements out of the list (that's it, modifying it in place)... – fortran Sep 09 '09 at 16:21
  • +1 to Adam Batkin really good comment in my opinion. I'll accept fortran answer even thought using the while/pop way I can eventually debug what's going away!!! – DrFalk3n Sep 09 '09 at 16:43
  • 7
    Also, "list" should not be used as a variable name, because is shadows the "list" type. Many Python developers use "L" as a list variable name, but I prefer "lst". – steveha Sep 10 '09 at 22:29
  • Shouldn't this answer be deleted as it is misleading? – Werner May 06 '16 at 01:22
  • 1
    Sometimes you just want the list emptied and this is as good as any of the methods proposed. Probably even faster – smac89 May 21 '16 at 22:10
  • I came to this page to empty an existing list. Naturally, this is the first thing I tried, but just as people pointed out, this didn't work. This just creates a new list and now your variable points to the new list. Your existing list doesn't get modified. I went with `list.clear()`. – akinuri Jan 15 '19 at 06:44
-3

Another simple code you could use (depending on your situation) is:

index=len(list)-1

while index>=0:
    del list[index]
    index-=1

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[0] remaining.

Donald
  • 633
  • 5
  • 16