Remove all elements from a list in Python using reinitializing, del and clear

Hello readers! In this article, we are going to learn how to remove all the elements from a list using various methods. Python provides many ways to remove all the elements from a list. Here, we will learn the following methods.

  • Using list.clear( ) method
  • Using del statement
  • By reinitializing the list

Removing elements using list.clear( ) method

Python list has an inbuilt method known as clear( ). This method helps us to removes all the elements from the list and its references. This method doesn’t take any parameters and it doesn’t return any value.
Syntax: list.clear( )

Program to understand the working of the list.clear( ) method

l=[1,2,3,4,5]
print("List before using the clear method:",str(l))
l.clear()
print("List after using the clear method:",str(l))

Output:

List before using the clear method: [1, 2, 3, 4, 5]
List after using the clear method: []

Removing elements using the del statement

In python, the del statement is mostly used to delete the objects. Since everything in python is an object, this statement can delete the portion of the list with the help of list slicing. This method affects the other references on the list.
Syntax: del list[:]

Here, list[:] represents the list elements from starting to end.

Program to understand the working of del statement

l=[1,2,3,4,5]
print("List before using del statement:",str(l))
del l[:]
print("List after using del statement:",str(l))

Output:

List before using the del statement: [1, 2, 3, 4, 5]
List after using the del statement: []

Removing elements by reinitializing the list

The simple way to remove the elements of a list is by reinitializing the original list with an empty list. This method doesn’t affect the other references of the list, unlike the above methods.
Syntax: original_list=[ ]

Program to understand the working of reinitializing

l=[1,2,3,4,5]
print("List before reinitializing:",str(l))
l=[ ]
print("List after reinitializing:",str(l))

Output:

List before reinitializing: [1, 2, 3, 4, 5]
List after reinitializing: []

That’s it! Hope you understood how to remove all elements from the list.
If you have any doubts, feel free to post them below.

Also do check out our other related articles below :

Leave a Reply

Your email address will not be published.