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?

5
  • 28
    So why do python dicts and sets have a clear() method, but not lists?
    – job
    Sep 9, 2009 at 16:59
  • 13
    But if there are multiple references to the object, it might be useful.
    – Ned Deily
    Sep 9, 2009 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, 2009 at 7: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, 2013 at 22:15
  • 4
    Notwithstanding any other, better answers, your initial code could have been written: while alist: alist.pop() Nov 24, 2014 at 18:54

7 Answers 7

587

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.

8
  • 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 9, 2009 at 16:24
  • 2
    For a sound explanation of del, I'd refer to the docs: docs.python.org/reference/simple_stmts.html#the-del-statement
    – fortran
    Sep 9, 2009 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 9, 2009 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 6, 2010 at 15:00
  • if we do l = [] won't the old list contents get garbage collected by Python GC ? Mar 15, 2016 at 12:00
213

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
2
  • 13
    This answer should be at top, whats wrong with stackoverflow!
    – BreakBadSP
    Aug 3, 2018 at 5:59
  • 1
    You made me laugh "Python 3.3 or better" hahaha. I agree with you, it is getting better (and I can't wait to ditch support for Python 2) ! Sep 22, 2022 at 12:39
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.

4
  • 6
    Why not just alist = []?
    – mitenka
    Feb 9, 2017 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) Feb 13, 2017 at 3: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 6, 2019 at 2: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. Jun 26, 2020 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
3
  • 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. Nov 7, 2012 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 5, 2016 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. Mar 13, 2017 at 1: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

1
  • 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, 2018 at 9:54
-3
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.

8
  • 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. Sep 9, 2009 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" Sep 9, 2009 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 9, 2009 at 16:21
  • 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, 2009 at 22:29
  • 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, 2016 at 22:10
-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.

2
  • 19
    reinventing the wheel with a cube Nov 24, 2016 at 22:06
  • 2
    Haha. This is the second weird answer (+ an appropriate comment) that I've encountered on SO. There should be a site for these memorable things :D
    – akinuri
    Jan 15, 2019 at 6:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.