Javaexercise.com

How To Empty a List In Python?

To make a list empty, we can use several ways such as del keyword, empty assignment, etc in Python.

In this article, we are going to see the solutions for making a list empty in python.

Empty a list using del in python

Here, we used the del keyword of python to clear or empty a list in python. The del keyword can be used to delete any object as well.

Here, we used the slicing approach to remove elements only.

# A list
list1 = [12,43,54,65,32,5]
print(list1)
del list1[:]
print(list1)

Output:

[12, 43, 54, 65, 32, 5]
[]

Empty a list using an empty assignment in Python

 This is another approach where we are assigning an empty list to the existing list to make the list empty. The empty square brackets ([]) represent an empty list in python.

# A list
list1 = [12,43,54,65,32,5]
print(list1)
list1[:] = []
print(list1)

Output:

[12, 43, 54, 65, 32, 5]
[]
 

Empty list using the clear() method in python

If you are working with python's latest versions then you can use a built-in clear() method as well. This is the list's built-in method so you can be called directly by using the list object.

# A list
list1 = [12,43,54,65,32,5]
print(list1)
list1.clear()
print(list1)

Output:

[12, 43, 54, 65, 32, 5]
[]

Empty list using unpacking assignment in python

# A list
list1 = [12,43,54,65,32,5]
print(list1)
list1 *=0
print(list1)

Output:

[12, 43, 54, 65, 32, 5]
[]