Remove all items from a Python list
This post will discuss how to remove all items from the list in Python. In other words, empty or delete a list in Python.
1. Using list.clear() function
list.clear() is the recommended solution in Python 3 to remove all items from the list.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] print(a) # prints [1, 2, 3, 4, 5] a.clear() print(a) # prints [] |
2. Using Slice assignment
You can empty the list by replacing all the elements with an empty list.
But simply doing a = [] won’t clear the list. It just creates a new list and binds it to the variable a, but the old list and its references remain in memory. For instance,
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] b = a print(a) # prints [1, 2, 3, 4, 5] a = [] print(a) # prints [] print(b) # prints [1, 2, 3, 4, 5] |
You can clear the entire list by assignment of an empty list to the slice, i.e., a[:] = [].
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] b = a print(a) # prints [1, 2, 3, 4, 5] a[:] = [] print(a) # prints [] print(b) # prints [] |
3. Using del statement
You can also use the del statement to delete the contents of an entire list. This is demonstrated below:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': a = [1, 2, 3, 4, 5] print(a) # prints [1, 2, 3, 4, 5] del a[:] print(a) # prints [] |
That’s all about removing all items from a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)