Python List clear() Method



The Python list clear() method is used to remove all elements from a list, effectively making it empty. The method modifies the list in place and does not return any value.

Any references to the elements that were previously in the list will be removed, and the memory they occupied will be deallocated by Python's garbage collector, freeing up resources.

Syntax

Following is the basic syntax of the Python List clear() method −

list.clear()

Parameter

This method does not accept any parameters.

Return Value

The method does not return any value. It modifies the original list by removing all its elements.

Example

In the following example, we are using the clear() method to remove all elements from the list "my_list", resulting in an empty list −

my_list = [1, 2, 3, 4, 5]
my_list.clear()
print("The list obtained is:",my_list)  

Output

The output obtained is as follows −

The list obtained is: []

Example

Here, we demonstrate that calling clear() on an already empty list has no effect −

empty_list = []
res = empty_list.clear()
print("The list obtained is:",res)  

Output

Following is the output of the above code −

The list obtained is: None

Example

In this example, we are clearing all elements from a list "mixed_list" containing mixed data types such as integers, strings, booleans, and another list −

mixed_list = [1, 'a', True, [5, 6]]
mixed_list.clear()
print("The list obtained is:",mixed_list)     

Output

The result produced is as shown below −

The list obtained is: []

Example

Now, we clear all elements from a list "list_of_lists", which contains references to other lists. After calling clear() method, all references are removed, and the list becomes empty −

list_of_lists = [[1, 2], [3, 4], [5, 6]]
list_of_lists.clear()
print("The list obtained is:",list_of_lists) 

Output

We get the output as shown below −

The list obtained is: []
python_list_methods.htm
Advertisements