Skip to content

Remove all elements from the list Python | Example code

  • by

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 the del statement will delete the whole list object. This useful Python trick will come in handy when you need to reset a list or create a fresh list for new data.

Example remove all elements from the list of 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 you 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]

Comment if you have any doubts or suggestions on this Python list code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

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