Python Clear a List



The clear() method in list class clears the contents of the given list. However, the list object is not removed from the memory. To remove the object from memory, use the "del" keyword.

Syntax

list.clear()

Example

The following example demonstrates how you can clear a list −

lst = [25, 12, 10, -21, 10, 100]
print ("Before clearing: ", lst)
lst.clear()
print ("After clearing: ", lst)
del lst
print ("after del: ", lst)

It will produce the following output

Before clearing: [25, 12, 10, -21, 10, 100]
After clearing: []
Traceback (most recent call last):
 File "C:\Users\mlath\examples\main.py", line 6, in <module>
  print ("after del: ", lst)
                        ^^^
NameError: name 'lst' is not defined. Did you mean: 'list'?

The NameError occurs because "lst" is no longer in the memory.

python_list_methods.htm
Advertisements