How to clear a list in Python
In this tutorial, we are going to learn about how to clear or empty a list of elements in Python.
Consider, we have the following list in our code:
users = ['john', 'nancy', 'salsa']
Now, we need to clear all elements from a above list like this []
.
Using clear() method
To clear a list, we can use the built-in clear()
method in Python.
Here is an example, that removes the all elements from a users
list:
users = ['john', 'nancy', 'salsa']
users.clear() #clears all elements
print(users)
Or we can also use the following slice syntax to do it.
users[:] = []