Python List clear() Method
Python List clear() method is used for removing all items from the List. The list clear() Method modifies the list in-place, i.e. It doesn’t create any copy of the list.
Python list clear() Method Syntax
Syntax: list.clear()
Parameters: The clear() method doesn’t take any parameters
Returns: list clear() method doesn’t return any value.
Python list clear() Method Example
Python3
lis = [1, 2, 3]lis.clear()print(lis) |
Output:
[]
Example 1: Working of list clear() Method
Python3
# Python program to clear a list# using clear() method# Creating listGEEK = [6, 0, 4, 1]print('GEEK before clear:', GEEK)# Clearing listGEEK.clear()print('GEEK after clear:', GEEK) |
Output:
GEEK before clear: [6, 0, 4, 1] GEEK after clear: []
Time complexity: O(1)
Auxiliary space: O(1)
Example 2: Clearing 2-D list using list clear() Method
Python3
# Defining a 2-d listlis = [[0, 0, 1], [0, 1, 0], [0, 1, 1]]# clearing the listlis.clear()print(lis) |
Output:
[]
Example 3: Using del Keyword vs list clear() Method
We can use the del keyword to delete the slice of a list from memory. But while using list.clear() Method, it modifies the list inplace by removing all elements of the list. Nevertheless, the output from both of the approaches are the same.
Python3
lis_1 = [1, 3, 5]lis_2 = [7, 9, 11]# using clear methodlis_1.clear()print("List after using clear():", lis_1)# using del to clear itemsdel lis_2[:]print("List after using del:", lis_2) |
Output:
List after using clear(): [] List after using del: []
Note: We are not directly using del lis_2, since it’ll delete the list object, but we want to delete the contents of the list, so we are deleting the slice of the list representing the complete list.
Time Complexity: O(1)
Auxiliary Space: O(1)






Please Login to comment...