Skip to content
Related Articles

Related Articles

Python List clear() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 13 Sep, 2022
View Discussion
Improve Article
Save Article

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 list
GEEK = [6, 0, 4, 1]
print('GEEK before clear:', GEEK)
 
# Clearing list
GEEK.clear()
print('GEEK after clear:', GEEK)


Output:

GEEK before clear: [6, 0, 4, 1]
GEEK after clear: []

Example 2: Clearing 2-D list using list clear() Method

Python3




# Defining a 2-d list
lis = [[0, 0, 1],
       [0, 1, 0],
       [0, 1, 1]]
 
# clearing the list
lis.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 method
lis_1.clear()
print("List after using clear():", lis_1)
 
# using del to clear items
del 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)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!