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 [] |
DownloadRun Code
2. Using Slice assignment
You can empty the list by replacing all the elements with an empty list.
But simply doing a = [] wont 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] |
DownloadRun Code
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 [] |
DownloadRun Code
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 [] |
DownloadRun Code
Thats all about removing all items from a list in Python.