How to Delete all elements from a Python list?

In this tutorial, you will learn how to delete all elements from a Python list in various ways.

Different ways to remove all elements from a Python List

1. Python list clear() method

With the help of the Python list clear() method, you can clear a Python list completely.

list.clear()

This method does not return anything, it simply removes all elements from the Python list.

>>> a = [1,2,3,4]
>>> a.clear()
>>> print(a)
[]
>>>

But the clear() method affects all the references. See the following example:-

In the following code, a list invoked the clear method but b also gets cleared. Because a and b are pointing to the same list.

>>> a = [1, 2, 3]
>>> b = a
>>> print(a, b)
[1, 2, 3] [1, 2, 3]
>>> 
>>> a.clear()
>>> print(a, b)
[] []
>>>

2. Assign a new empty list to the variable

You can assign a new empty list to the variable, and it does not affect the references.

a = []
>>> a = [1, 2, 3]
>>> b = a
>>> print(a, b)
[1, 2, 3] [1, 2, 3]
>>> 
>>> a = []
>>> print(a, b)
[] [1, 2, 3]
>>>

3. Use del statement to empty a Python list

The del statement is also can remove all elements from a Python list, but it also affects the references.

del a[:] # delete statement with slice (:) operator
>>> a = [1, 2, 3]
>>> b = a
>>> print(a, b)
[1, 2, 3] [1, 2, 3]
>>> 
>>> del a[:]
>>> print(a, b)
[] []
>>>

Leave a Reply

Your email address will not be published. Required fields are marked *