Python List is used to storing multiple items in a single variable. These items can be added and removed easily. The Python List clear() method is used to remove all items or clear the list. In this tutorial, we will learn how to use Python list clear() method usage and alternative ways to clear a Python list.
clear() Method Syntax
The Python List clear method has very simple syntax. It does not accept any parameter. The clear() method can be used for Python 3.3 and later versions. If you are using Python2 and Python 3.2 and lower you can use the del statement which is decrribed below.
LIST.clear()
- LIST is the list we will clear where remove all items.
The clear() method do not returns any value.
Clear List (Remove All Items)
The clear() method can be used to clear list or remove all items with a single line of command. The list item count and type is not important. Just call the clear() method from the list.
names = ["ismail","ahmet","ali"]
names.clear()
print(names)
The output is nothing becuase all the items in the names are cleared.
Clear List Reinitializging
Python list items can be cleared by reinitializing the list as an empty list. This is like creating a new list. The [] is used to specify an empty list that is assigned to the existing list.
names = ["ismail","ahmet","ali"]
names= []
print(names)
Clear List with “*=0”
The “*=0” method is a less known method that removes all items of the given list and empties the list. It is like zeroing the list.
names = ["ismail","ahmet","ali"]
names *=
0
print(names)
Clear List with del Statement
The del statement is another popular way to clear a list and remove all items. The clear() method can not be used in Python2 or Python3.2 and lesser but the del can be used for all Python versions to empty a list. The del can remove a single item from the list but if all items are specified all items are removed. The names[:] specify all items. The list also provided after the del statement.
names = ["ismail","ahmet","ali"]
del names[:]
print(names)