More Methods to clear a List
ln below examples we will empty a list using the clear function in Python:
1. Empty a List using clear() Method
In this example, we are creating a list, and we print it before clearing and after clearing in Python.
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) |
GEEK before clear: [6, 0, 4, 1] GEEK after clear: []
2. Emptying the List Using del
In this example, we are creating a 2D list, and we are using the del keyword to delete the list data.
Python3
my_list = [ 1 , 2 , 3 , 4 , 5 ] del my_list[:] print (my_list) |
[]
3. Clearing 2D list using list clear() Method
In this example, we are creating a 2D list, and we are clearing the list at all indexes of the 2D list and printing it.
Python3
# Defining a 2-d list lis = [[ 0 , 0 , 1 ], [ 0 , 1 , 0 ], [ 0 , 1 , 1 ]] # clearing the list lis.clear() print (lis) |
[]
4. Clearing 2D list with specific index using list clear() Method
In this example, we are creating a 2D list, and we are clearing the list at the first index of the 2D list and printing it.
Python3
# Defining a 2-d list lis = [[ 0 , 0 , 1 ], [ 0 , 1 , 0 ], [ 0 , 1 , 1 ]] # clearing the list lis[ 0 ].clear() print (lis) |
[[], [0, 1, 0], [0, 1, 1]]
5. 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 the list.clear() method, it modifies the list in place by removing all elements of the list. Nevertheless, the output from both approaches is 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) |
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.
We have discussed the definition, syntax, and examples of the list clear() method in Python. We also looked at other methods used to clear a list. The list clear() function is a very useful function of list methods as it helps us to re-use a list.
Read Other Python List Methods
Also Read:
Python List clear() Method
Python List clear() method removes all items from the List making it an empty/null list.
Example
Python3
lis = [ 1 , 2 , 3 ] lis.clear() print (lis) |
[]
Contact Us