Remove all elements from the list Python | Example code

Use the clear() function to remove all elements from the list in Python. You can also use the Slice assignment to empty the list by replacing all the elements with an empty list.

Using del statement will delete the whole list object.

Example remove all elements from the list Python

Simple example code removes, empty, or deletes a list in Python.

Using list.clear() function

It is recommended solution.

a = [1, 2, 3, 4, 5]

print(a)
a.clear()

print(a)

Output:

Remove all elements from the list Python

Using Slice assignment

Simply doing a = [] won’t clear the list. It just creates a new list and binds it to the variable a, but the old list and its references remain in memory.

a = [1, 2, 3, 4, 5]
old = a

print(a)
a = []

print(a)
print(old)

Output:

[1, 2, 3, 4, 5]
[]
[1, 2, 3, 4, 5]

But clear the entire list by assignment of an empty list to the slice, i.e., a[:] = [].

a = [1, 2, 3, 4, 5]
old = a

print(a)
a[:] = []

print(a)
print(old)

Using del keyword

It will delete the list object, an error will throw if try to access it after deleted.

a = [1, 2, 3, 4, 5]

print(a)
del a

print(a)

Output:

NameError: name ‘a’ is not defined
[1, 2, 3, 4, 5]

Do comment if you have any doubts and suggestions on this Python list code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.