Given a list, the task is to remove all elements from it. For Example:
Input: [10, 20, 30, 40]
Output: []
Let's explore diiferent methods to clear a list in Python.
Using clear() Method
clear() empties the list directly by removing all elements from the same list object.
a = [1, 2, 3, 4, 5]
a.clear()
print(a)
Output
[]
Explanation:
- clear() removes all elements from the list a in place.
- The list object remains the same, only its contents are erased.
Using del a[:]
del a[:] deletes every element inside the list using slicing while keeping the same list reference.
a = [1, 2, 3, 4, 5]
del a[:]
print(a)
Output
[]
Explanation:
- a[:] selects the entire list.
- del a[:] deletes all selected elements, leaving the list empty.
Using a Loop with pop()
This method removes elements one by one until the list becomes empty using pop(). It works but is the slowest option.
a = [1, 2, 3, 4, 5]
while a:
a.pop()
print(a)
Output
[]
Explanation:
- a.pop() removes the last element in each iteration.
- Loop continues until the list becomes empty.
Reassigning to []
Assigning the name to a new empty list does not modify the old list, it simply makes the variable point to a fresh empty list.
a = [1, 2, 3, 4, 5]
a = []
print(a)
Output
[]
Explanation:
- a = [] assigns a new empty list to the variable a.
- The old list still exists if referenced elsewhere.
Note: Using a = [] does not clear the original list - it only reassigns the variable to a new empty list. If other variables reference the same list, they will still hold the old data.