In this article, we will show how to write a Python program to clear the list items with examples. There are three options that one can use to clear the list items, and they are the clear() method, del, and empty list.
Python Program to Clear a List
In the program below, we have declared a list of integer values. Next, we use the list clear() function that will clear or remove all the list items and print the empty one.
a = [10, 20, 30, 40, 50]
print(a)
a.clear()
print(a)
[10, 20, 30, 40, 50]
[]
The below program uses the del function that will remove a single item based on the index. However, you can use the below approach to clear all the existing list items in one go.
a = [10, 20, 30, 40, 50]
del a[:]
print(a)
[]
Apart from the above two approaches, you can reassign the existing list to an empty list approach. It will automatically clear the existing list items. Remember, to delete the individual items, use the remove function.
a = [10, 20, 30, 40, 50]
print(a)
a = []
print(a)
[10, 20, 30, 40, 50]
[]
The other option is to assign the slice of the existing list (empty) to itself.
a = [10, 20, 30, 40, 50]
print(a)
print(a[:])
a[:] = []
print(a)
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
[]
Python Program to Clear a List using loops
If you want to remove or clear one item at a time, try the for loop or while loop along with the remove or pop functions.
a = [10, 20, 30, 40, 50]
print(a)
for i in range(len(a)):
a.pop()
print(a)