Python List clear()

Python list‘s clear() function method is used to delete all the items from the list.


Syntax

Here list1 is object of the list.


Return

It does not return any value.It will remove all the items from the list.


Example

Let’s see a very simple example:

listOfVehicles= ['Car','Truck','Bike'] print("listOfVehicles before calling clear method:",listOfVehicles) listOfVehicles.clear() print("listOfVehicles after calling clear method:",listOfVehicles)

Output:

listOfVehicles before calling clear method: [‘Car’, ‘Truck’, ‘Bike’]
listOfVehicles after calling clear method: []

Note: If you are using Python 2 or Python 3.2 and below, you need to use del operator as clear method is not available.

listOfVehicles= ['Car','Truck','Bike','Cycle'] print("listOfVehicles before calling clear method:",listOfVehicles) del listOfVehicles[:] print("listOfVehicles after calling clear method:",listOfVehicles)

Output:

listOfVehicles before calling clear method: [‘Car’, ‘Truck’, ‘Bike’, ‘Cycle’]
listOfVehicles after calling clear method: []

That’s all about Python List’s clear() method.

Leave a Reply

Your email address will not be published. Required fields are marked *