clear() method is used to remove all elements from a list. It empties the list completely while keeping the original list object unchanged.
In this example, clear() removes all items from the list.
a = [1, 2, 3]
a.clear()
print(a)
Output
[]
Explanation: clear() removes all elements from list a, making it an empty list.
Syntax
list.clear()
Examples
Example 1: In this example, the list contains sublists. Calling clear() removes all nested elements from the main list.
a = [[1, 2], [3, 4], [5, 6]]
a.clear()
print(a)
Output
[]
Explanation: clear() removes all sublists stored inside list a.
Example 2: Here, the list is cleared and then reused to store new values without creating a new list.
a = [10, 20, 30]
a.clear()
a.append(40)
print(a)
Output
[40]
Explanation: After clear() empties the list, append(40) adds a new element to the same list.