Last Updated : 18 Dec, 2024
clear()
method in Python is used to remove all elements from a list, effectively making it an empty list. This method does not delete the list itself but clears its content. It is a simple and efficient way to reset a list without reassigning it to a new empty list.
Example:
Python
a = [1, 2, 3]
# Clear all elements from the list 'a'
a.clear()
print(a)
clear()
method removes all the elements from the numbers
list, leaving it empty.clear()
Method
Parameters:list.clear()
clear()
method does not take any parameters.None
).clear()
Method 1. Clearing a list of strings
clear()
method can be used to remove all elements from a list of strings, leaving it empty. This is helpful when we want to reuse the list later without creating a new reference.
a = ["Geeks", "for", "Geeks"]
# Clear all elements from the list 'a'
a.clear()
print(a)
Explanation:
clear()
method empties the words
list while keeping the variable words
intact.When working with a list that contains other lists (nested lists), calling clear()
on the parent list removes all the inner lists as well, effectively clearing the entire structure but keeping the reference to the parent list intact.
a = [[1, 2], [3, 4], [5, 6]]
# Clear all elements from the list 'a'
a.clear()
print(a)
Explanation:
clear()
method removes all elements, including nested ones.By using clear()
, we can empty a list without creating a new list or breaking any references to it. This is useful when we want to clear the contents of a list while keeping the variable name and its references intact for future use.
a = [10, 20, 30]
# Clear all elements from the list 'a'
a.clear()
print(a)
Explanation:
clear()
Method 1. Reusing a List:
clear()
method allows us to empty a list without creating a new one, making it easy to reuse the same list for storing new data.
a = [10, 20, 30]
# Clear all elements from the list 'a'
a.clear()
a.append(40)
print(a)
2. Memory Optimization:
Using clear()
helps in releasing the memory held by the elements of the list, making it available for other operations without creating a new list object.
a = [i for i in range(1_000_000)]
# Clear all elements from the list 'a'
a.clear()
print(a)
Python program to clear a list
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4