How to Clear a List in Python
To clear a list in Python, you can use the clear() method, the del statement, or by reassigning an empty list.
The following examples show how to clear a list in Python.
Using clear() Method
We can use the clear() method to remove all items from a list.
Suppose we have the following list:
# Declare list
office_stuff = ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse']
# Clear the list
office_stuff.clear()
# Show the cleared list
print(office_stuff)
Output: 👇️
[]
In this example, we use the clear() method to remove all items from the list office_stuff.
Using del Statement
We can use the del statement to remove all items from a list.
Suppose we have the following list:
# Declare list
office_stuff = ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse']
# Clear the list
del office_stuff[:]
# Show the cleared list
print(office_stuff)
Output: 👇️
[]
In this example, we use the del statement to remove all items from the list office_stuff.
Reassigning an Empty List
We can reassign an empty list to clear all items from a list.
Suppose we have the following list:
# Declare list
office_stuff = ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse']
# Clear the list
office_stuff = []
# Show the cleared list
print(office_stuff)
Output: 👇️
[]
In this example, we reassign an empty list to office_stuff to clear all items from the list.
Conclusion
We can use the clear() method, the del statement, and reassigning an empty list to clear a list in Python. These methods provide a convenient way to remove all items from a list.