How to clear a list in python?

This article discusses the different methods to clear a list in python.

Clearing a list by using the clear() method

Consider a list list_1 = [1, "apple", 3, "red"]. list_1.clear() delete all the items in the list and returns an empty list.

list_1 = [1, "apple", 3, "red"]
print("list_1: ", list_1)
list_1.clear()
print("list_1: ", list_1)

The above code returns the output as

list_1:  [1, 'apple', 3, 'red']
list_1:  []

Clearing a list by reinitializing the list to an empty list

The list can be reinitialized to an empty list to clear all the items in the list.

list_1 = [1, "apple", 3, "red"]
print("list_1: ", list_1)
list_1 = [] # reinitializing with an empty list
print("list_1: ", list_1)

Output

list_1:  [1, 'apple', 3, 'red']
list_1:  []

Clearing a list by using a del statement

The del statement removes specified items from the list. Consider a list list_1 = [1, "apple", 3, "red"]. The del list_1[:] removes all the items in the list and makes the list empty. [:] is equivalent to [0 : len(list_1)].

list_1 = [1, "apple", 3, "red"]
print("list_1: ", list_1)
del list_1[:]
print("list_1: ", list_1)

Output

list_1:  [1, 'apple', 3, 'red']
list_1:  []​

Clearing a list by multiplying the list with 0

Multiplying the list with 0 clears the data items in the list.

list_1 = [1, "apple", 3, "red"]
print("list_1: ", list_1)
list_1 = list_1*0
print("list_1: ", list_1)

The above code returns an empty list.

list_1:  [1, 'apple', 3, 'red']
list_1:  []

Clearing a list by using the while loop and pop() function

Consider a list list_1 = [1, "apple", 3, "red"]. A while loop iterates till the list is not empty. In each iteration, the pop() function removes the last element from the list resulting in an empty list.

list_1 = [1, "apple", 3, "red"]
print("list_1: ", list_1)
while list_1:
    list_1.pop()
print("list_1: ", list_1)

The above code returns the output as

list_1:  [1, 'apple', 3, 'red']
list_1:  []
We can calculate the length of the list and then use a for loop to remove all the items from the list with the help of pop() function
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions