Different ways to clear a list in Python


Clearing up all the elements in a python list can be done in many ways. Below are the some of the methods which are implemented to achieve this.

using clear()

This function is a part of standard library and empties the python list completely.

Syntax: list_name.clear()
list_name is the name of the list supplied by

Example

In the below example we take a list and apply the clear (). The result is an empty list.

list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
#clear the list
list.clear()
print("After clearing the list\n")
print(list)

Output

Running the above code gives us the following result −

Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After clearing the list
[]

Using del()

The del() function you can selectively remove items at a given index or you can also remove all the elements, making the list empty.

Syntax: del list_name

In the below example we take a list, remove the element at index 2. Then we remove all the elements.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
#deleting one element from the list
del list[2]
print("After deleting an element\n")
print(list)
# Removing all elements
del list[:]
print("After deleting all elements\n")
print(list)

Output

Running the above code gives us the following result −

Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After deleting an element
['Mon', 'Tue', 'Thu']
After deleting all elements
[]

Using *=0

In this approach we just assign 0 to all elements in the list which makes the list empty. The * is a character representing all elements.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
# Removing all elements
list *= 0
print("After deleting all elements\n")
print(list)

Output

Running the above code gives us the following result −

Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After deleting all elements
[]

List Re-Initialization

We can re-initialize a list by just assigning an empty list to it. In the below example we take a list and then assign an empty list to it which creates an empty list.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu']
print("Existing list\n",list)
# Removing all elements
list = []
print("After deleting all elements\n")
print(list)

Output

Running the above code gives us the following result −

Existing list
['Mon', 'Tue', 'Wed', 'Thu']
After deleting all elements
[]

Updated on: 07-Aug-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements