![]() |
Python List clear() method removes all items from the List making it an empty/null list. Example Python3
Output
[] What is List clear() Method?list clear() is an in-built function in Python, that is used to delete every element from a list. It can make any list into a null list and should be used with caution. It is one of the most basic and known list operations. It is very useful for re-using a list, as you can delete every element from that list. List clear() Syntax
ParametersThe clear() method doesn’t take any parameters Returnslist clear() method doesn’t return a new list. How to Use clear() Function in PythonThe clear() function is very easy to use, just call it with a list you want to empty. Let’s understand how to clear a list with an example: Python3
Output
[] More Methods to clear a Listln below examples we will empty a list using the clear function in Python: 1. Empty a List using clear() MethodIn this example, we are creating a list, and we print it before clearing and after clearing in Python. Python3
Output
GEEK before clear: [6, 0, 4, 1] GEEK after clear: [] 2. Emptying the List Using delIn this example, we are creating a 2D list, and we are using the del keyword to delete the list data. Python3
Output
[] 3. Clearing 2D list using list clear() MethodIn 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
Output
[] 4. Clearing 2D list with specific index using list clear() MethodIn 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
Output
[[], [0, 1, 0], [0, 1, 1]] 5. Using del Keyword vs list clear() MethodWe 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
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. 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.
Also Read:
|
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |