In Python, the clear()
method is used to remove all elements from a list, essentially making it an empty list. It is a built-in method available for lists in Python.
Here's the basic syntax of the clear()
method:
list_name.clear()
list_name
: This is the name of the list from which you want to remove all elements.Let's see an example of using the clear()
method:
# Create a list with some elements
my_list = [1, 2, 3, 4, 5]
# Clear the list (remove all elements)
my_list.clear()
print(my_list) # Output: []
As you can see, after calling the clear()
method on the list, all its elements are removed, leaving an empty list. It's a useful method when you want to reset or reinitialize a list to an empty state.