Learnitweb

How to clear a list in Python

We’ll discuss different ways to clear a list in Python. The 4 ways which we’ll discuss to clear the list are:

  • Using clear() method
  • Using *= 0
  • Using del() method
  • Reinitializing the list

Method 1: Using clear() method

We can use clear() method to clear the list.

# Python program to clear list using clear() 

# creating list
listToClear = [1,2,3,4,5]
print('list before clear', listToClear)

# clear list
listToClear.clear()
print('list after clear', listToClear)

Output

list before clear [1, 2, 3, 4, 5]
list after clear []

Method 2: Using *=0

This is not so common way to clear the list. Let us see this with an example.

# creating list
listToClear = [1,2,3,4,5]
print('list before clear: ', listToClear)

# clear list 
listToClear *= 0
print('list after clear using *=0: ', listToClear)

Output

list before clear:  [1, 2, 3, 4, 5]
list after clear using *=0:  []

Method 3: Using del()

del() method when used without the range can clear the entire list.

# Python program to clear list using del() 

# creating list
listToClear = [1,2,3,4,5]
print('list before clear: ', listToClear)

# clear list
del listToClear[:]
print('list after clear using del(): ', listToClear)

Output

list before clear:  [1, 2, 3, 4, 5]
list after clear using del():  []

Method 4: Reinitializing the list

This method creates an empty list and assigns to the variable. So the references to the original list will be impacted.

# Python program to clear list using reinitialization 

# creating list
listToClear = [1,2,3,4,5]
print('list before clear: ', listToClear)

# clear list
listToClear = []
print('list after reinitialization: ', listToClear)

Output

list before clear:  [1, 2, 3, 4, 5]
list after reinitialization:  []