Ways to clear a Python List

A list in Python is a collection that is mutable, ordered, and changeable. Here we are going to see the various ways that are available to clear a Python list. Below are some of the easiest methods to clear all the elements in a list.

Method 1: Using clear() method

To clear all elements from the list, we can use the clear() method.

  • Syntax: list.clear()
  • Parameters: No parameters.

Let’s have a look at the example program.

list1=[1,"codespeedy",3,-2,"welcome"]
print("Before clearing list:")
print(list1)
list1.clear()
print("After clearing list:")
print(list1)

Output:

Before clearing list:
[1, 'codespeedy', 3, -2, 'welcome']
After clearing list:
[ ]

Method 2: Using del keyword

del keyword: used to delete┬áthe elements of a list in a given range. If we didn’t mention the range, then all elements will be deleted.

  • Syntax: del obj_name
  • obj_name can be variables, user-defined objects, lists, dictionaries, etc.

Now, we have a look at the example program.

list1=[1,3,-2,6,10]
print("Before clearing list:")
print(list1)
del list1[:]
print("After clearing list:")
print(list1)

Output:

Before clearing list:
[1, 3, -2, 6, 10]
After clearing list:
[ ]

Method 3: Using “*=0”

This method is not a very popular one. All the elements in a list can be removed using this method.

Let’s see how to use it in a program.

list1=["Welcome","To","Codespeedy"]
print("Before clearing list:")
print(list1)
list1*=0
print("After clearing list:")
print(list1)

Output:

Before clearing list:
['Welcome', 'To', 'Codespeedy']
After clearing list:
[ ]

Method 4: Reinitializing the list

In this method, we re-initialize a list just by assigning an empty list to it.

Let’s have a look at the implementation.

list1=["India","Australia","England","New Zealand"]
print("Before clearing list:")
print(list1)
list1=[]
print("After clearing list:")
print(list1)

Output:

Before clearing list:
['India', 'Australia', 'England', 'New Zealand']
After clearing list:
[ ]

I hope that you have learned something new from here.

Leave a Reply

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