Python List clear() Method

The clear() method in Python is a built-in function used to remove all the elements of a list. This method empties the list and returns nothing. The clear() method is used to quickly remove all elements from a list, without having to create a new list and copying all the elements over one by one.

Syntax

list.clear()

Parameters

The clear() method does not take any parameters.

Examples

Example 1: Clearing a List

Let’s consider a list of numbers and use the clear() method to remove all the elements:

numbers = [1, 2, 3, 4, 5]
numbers.clear()
print(numbers)

In this example, we have created a list of numbers called numbers. Then, we have used the clear() method to remove all the elements from the list. Finally, we have printed the list, which will be an empty list: [].

Example 2: Clearing a List with For Loop

Let’s consider the same list of numbers and remove all the elements using a for loop:

numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
    numbers.pop()
print(numbers)

In this example, we have used a for loop to iterate through the length of the list and remove each element using the pop() method. The pop() method removes the last element of the list by default. Finally, we have printed the list, which will be an empty list: [].

Example 3: Clearing a List with Slicing

Let’s consider the same list of numbers and remove all the elements using slicing:

numbers = [1, 2, 3, 4, 5]
numbers[:] = []
print(numbers)

In this example, we have used slicing to assign an empty list to the original list. This effectively removes all the elements from the list. Finally, we have printed the list, which will be an empty list: [].

In conclusion, the clear() method is a simple and convenient way to remove all the elements of a list. However, other methods such as for loops or slicing can also be used to achieve the same result.

Leave a Reply

Your email address will not be published. Required fields are marked *