How to remove all elements from a list in Python

Here in this tutorial, we are going to learn how to remove all elements from a list in Python. We can think of doing this in many ways. But here in this tutorial you will learn how to remove elements from a list using clear() and del().

Let us now start our tutorial.

Code to Remove all elements from a list in Python

Now, let us see how del() keyword is used to remove all elements from a list in Python.

del()

This method deletes all the elements in the range given. This del keyword deletes variables, lists, or parts of list, etc., Other similar keywords like pop(), remove() deletes elements in a particular range given but not all elements in a list.

The del() removes all elements from the list in Python. Let us see this through code now.

l=[1,2,7,8]
del l[0:4]
print(l)

OUTPUT:

[]

Now, let us see the usage of del() in another example also.

a=[1,2,'5','hi','&']
del a[0:5]
print(a)

OUTPUT:

[]

clear()

Now, let us see how to use clear() to remove all elements from a list.

The clear() method deletes all elements in a list. It doesn’t take any parameters. It doesn’t return any value also. This clear() deletes all elements from the list, set, dictionary etc., This is the easy way of deleting elements in Python.

Now, let us see this using example.

m=[2,6,5,9,17,34]
m.clear()
print(m)

OUTPUT:

[]

Let us see this through another example.

a=[2,6,5,'u','7']
print(a.clear())
print(a)

OUTPUT:

None
[]

So, we have seen how to delete elements in a list in two ways in this tutorial.

You may learn:

Leave a Reply

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