How to Clear All Elements in a List in Python?

Estimated read time 1 min read

In Python, you can clear all elements in a list by using the clear() method. The clear() method removes all the elements from a list, leaving it empty.

Here’s an example of how to use the clear() method to clear all elements in a list:

my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list) # Output: []

In this example, the clear() method is called on the my_list object, which removes all the elements from the list, leaving it empty.

Note that the clear() method modifies the original list in place and does not return a new list. If you want to create a new list with the same name as the original list, you can simply assign an empty list to it like this:

my_list = [1, 2, 3, 4, 5]
my_list = []
print(my_list) # Output: []

This creates a new empty list and assigns it to the my_list variable, effectively clearing all elements from the original list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply