How To Clear A List In Python

In this tutorial, we will learn how to clear a list in Python. Clearing a list is useful when you want to remove all elements from a list, making it an empty list. Python provides several ways to achieve this, and we will be discussing four methods: the del keyword, the clear() function, the * operator, and using list slicing.

Method 1: Using the del keyword

The del keyword is used to delete a list or a part of the list. It can also be used to delete elements from a list. Use the following syntax to delete the entire list:

Here’s an example:

[]

As you can see, the list is now empty.

Method 2: Using the clear() function

The clear() function is another way to clear a list in Python. It removes all elements from the list. The syntax is as follows:

Here’s an example:

[]

The list has been cleared successfully using the clear() function.

Method 3: Using the * operator

In Python, the * operator can be used to create a new list by repeating an existing one. To clear a list, simply multiply the original list by 0, like this:

Here’s an example:

[]

The list is now empty.

Method 4: Using list slicing

List slicing is another method to clear a list in Python. The syntax for list slicing is as follows:

Here’s an example:

[]

The list has been successfully cleared using list slicing.

Full code

Conclusion

In this tutorial, we explored four ways to clear a list in Python: using the del keyword, the clear() function, the * operator, and list slicing. All of these methods have their own advantages, and you can choose any of them based on your preferences. Now you are ready to clear lists efficiently in your Python programs.