This tutorial shows 2 methods to clear a list in Python using examples.
Method 1: Use clear() to empty a list
You can use the method of clear()
to empty a list in Python. The following is an example.
cars=["Tesla", "Ford", "Toyota"]
print(cars)
['Tesla', 'Ford', 'Toyota']
# Empty the list of cars in Python using clear()
cars.clear()
print(cars)
[]
Method 2: Use Del to clear or empty a list
You can use del to clear or empty a list as well. The following is the Python code example.
cars=["Tesla", "Ford", "Toyota"]
# Before using del
print("Before using del: \n", cars)
del cars[:]
# After using the del
print("Before using del: \n", cars)
Before using del: ['Tesla', 'Ford', 'Toyota'] Before using del: []