Python Clearing a List

Clearing a List in Python

The clear() method in the list class clears the contents of a given list. However, the list object is not deleted from memory. To delete an object from memory, use the “del” keyword.

Syntax

list.clear()

Example

The following example demonstrates how to 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:Usersmlathexamplesmain.py", line 6, in <module>
  print ("after del: ", lst)
                        ^^^
NameError: name 'lst' is not defined. Did you mean: 'list'?

The NameError occurs because “lst” no longer exists in memory.

Leave a Reply

Your email address will not be published. Required fields are marked *