Python List clear Function

This Python function is used to clear or remove total items from a list and the syntax of it is

list_name.clear()

Python List clear Example

In this example, we declared a string and the integer list. Next, we used a clear function on them to remove all the elements from them.

a = [10, 20, 30, 40]
Fruits = ['Apple', 'Banana', 'Kiwi', 'Grape']

print("Before : ", a)
a.clear()
print("After  : ", a)

print("\nBefore : ", Fruits)
Fruits.clear()
print("After  : ", Fruits)
Before :  [10, 20, 30, 40]
After  :  []

Before :  ['Apple', 'Banana', 'Kiwi', 'Grape']
After  :  []

This method deletes all the existing items. After executing this Python clear method, it returns an empty list.

Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
numbers = [9, 4, -5, 0, 22, -1, 2, 14]

print(Fruits)
print(numbers)

New_Fruits = Fruits.clear()
print("\nNew  : ", New_Fruits)

new_numbers = numbers.clear()
print("New Number : ", new_numbers)
['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
[9, 4, -5, 0, 22, -1, 2, 14]

New :  None
New Number :  None

TIP: Please refer to the List and functions article in Python.

In this program, we are allowing the user to enter the length of it. Next, we used For Loop to append those numbers. Then we used this method to delete the items.

intClearList = []
 
number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    intClearList.append(value)
    
print("Before Clear() - Items in this List are : ", intClearList)
intClearList.clear()
print("After Clear()  - Items in this List are : ", intClearList)
Python Clear List Function 3

It allows users to enter their own string or words, and then it removes those items. You can also use it on Mixed and Nested.

str1 = []
 
number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, number + 1):
    value = input("%d Element : " %i)
    str1.append(value)
    
print("Before = ", st1)
str1.clear()
print("After  = ", str1)
Please enter the Total Number of Elements: 4
1 Element : Dragon
2 Element : Cherry
3 Element : Kiwi
4 Element : Banana
Before  =  ['Dragon', 'Cherry', 'Kiwi', 'Banana']
After   =  []