Python

clear() method in list

Click for All Topics

clear() method in list - Python

  • This method is used to remove all elements from a list.
  • The .clear() method doesn’t take any argument and it doesn’t return anything.
  • When we call this method with an empty list then it doesn’t give any error.
  • When we call this method with a list it will traverse each element, removes the reference of each element from the list and make the length of the list 0.
  • The time complexity of this method is O(n) where n is the number of elements in the list.
  • This method is useful when you want to reset your list or you want to reinitialize the list.

 

Syntax –

list.clear()

 

Parameters –

  • argument → Doesn’t take any argument.
  • return → None(doesn’t return anything).

 

Example 1-

				
					my_list=[5,10,15,20,25,30]
print("Original list:",my_list)
my_list.clear()
print("Original list after clear:",my_list)

# Output -
# Original list: [5, 10, 15, 20, 25, 30]
# Original list after clear: []
				
			
  • In the above example, first we create a list with some elements and store it in my_list variable.
  • After creating my_list print the list on the output screen.
  • Then call the .clear() method with the my_list.
  • Finally, print the modified original list on the output screen.

Example 2- Clear an Empty list

				
					lst=[]
print("Original list:",lst)
lst.clear()
print("Modified original list:",lst)

# Output -
# Original list: []
# Modified original list: []