Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to empty a list?

Tags:

python

list

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

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

Does a clear way exist to do that?

like image 788
DrFalk3n Avatar asked Sep 09 '09 16:09

DrFalk3n


People also ask

How do you empty list?

You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

How do you empty an entire list in Python?

The clear() method removes all items from the list.

How do I remove values from a list?

Using del() The del() function you can selectively remove items at a given index or you can also remove all the elements, making the list empty. In the below example we take a list, remove the element at index 2.

What does list Clear () function do in Python?

The clear() method removes all the elements from a list.


2 Answers

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.

like image 81
fortran Avatar answered Sep 20 '22 17:09

fortran


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
like image 45
Eugene Yarmash Avatar answered Sep 20 '22 17:09

Eugene Yarmash