How to Delete a List in Python

In Python, lists are very flexible and can store different types of elements, and you can add, remove, and alter list elements as you wish. However, there may be scenarios where you find the need to delete a list completely. This tutorial will guide you on how to delete a list in Python.

Step 1: Understand Python Lists

A list is one of the Python’s most powerful data types. It can hold ordered and changeable items, and it allows duplicate members. Lists are created by placing all the items (elements) inside a square bracket [ ], separated by commas.

Here is an example of a Python list:

Step 2: Deleting a List Using the ‘del’ Keyword

The Python del keyword is a statement that removes a variable or item from the memory. This keyword can be used to delete a list in Python. Let’s illustrate this with a code:

After doing this, if you try to access or print ‘my_list’, Python will throw a NameError because ‘my_list’ no longer exists.

Step 3: Deleting a List Using the Clear() Method

Another way to delete a list is by using the clear() method. This method removes all items from the list, essentially making it an empty list.

After doing this, ‘my_list’ will still exist in memory, but it will be an empty list.

Full Code

Here is the full code demonstrating the two ways to delete a list in Python:

Conclusion

In this tutorial, you learned how to delete a list in Python. You were introduced to using the del keyword and the clear() method to achieve this.

While both ways effectively erase the list contents, the clear() method merely removes all the items in the list leaving an empty list, while the del keyword completely removes the list from memory.

Your choice of method depends on whether you want to reuse the list name again in your code or not.