The list
is a container data type that represents a collections of ordered elements.
Lists are mutable meaning that operations such as insertions and deletions can be performed on them in-place. The clear()
method is used to remove all elements from a list. The method is only available in versions of Python starting from Python3.3 and higher so you cannot use it in earlier versions.
#a list of strings
mylist = ['Python', 'Java', 'C++', 'Ruby']
#remove all elements from the list
mylist.clear()
#the list is now empty
print(mylist)
The syntax of the clear()
function is as shown below.
lst.clear()
The clear()
method takes no argument, when called, it simply empties the list and returns None
.
mylist = [1, 2, 3, 4, 5, 6, 7]
mylist.clear()
print(mylist)
Clearing a list in Python3.2 and earlier versions
As mentioned above, the clear()
method is not available in Python 2 and Python 3.2 and earlier versions. We can however use the del
statement to conveniently clear a list.
#a list of strings
mylist = ['Python', 'Java', 'Ruby', 'C++']
#clear the list
del mylist[:]
#the list is now empty
print(mylist)
The del
statement is used to delete objects. When used with a list slice, it will delete the items specified by the slice from the list.In the above example we used the del
statement above with a slice that references all the list items i.e del mylist[:]
.The outcome is that all items are deleted from the list effectively turning the list into an empty list.