Python List clear Function

Python clear List is used to clear or remove total items from a list. The syntax of the list clear function is

list_name.clear()

The below code removes items from the list a.

# Python Clear List Function

a = [10, 20, 30, 40]

print("Before Clear() - Items in this List are : ", a)
a.clear()
print("After Clear()  - Items in this List are : ", a)

List clear function output

Before Clear() - Items in this List are :  [10, 20, 30, 40]
After Clear()  - Items in this List are :  []

Python List clear Example

In this list clear example, we declared a string list. Next, we used a clear function on it.

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

# Python Clear List Function

Fruits = ['Apple', 'Banana', 'Kiwi', 'Grape']

print("Before Clear() - Items are : ", Fruits)
Fruits.clear()
print("After Clear()  - Items are : ", Fruits)

List clear function output

Before Clear() - Items are :  ['Apple', 'Banana', 'Kiwi', 'Grape']
After Clear()  - Items are :  []

List clear Function Example 2

In this python program, we are allowing the user to enter the length of a List. Next, we used For Loop to append those numbers to the list. Then we used the list clear function to clear the list items.

# Python Clear List Function

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

List clear Function Example 3

This Python list clear program allows users to enter their own string or words, and then it clears those items

# Python Clear List Function

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

List clear function output

Please enter the Total Number of List Elements: 4
Please enter the Value of 1 Element : Dragon
Please enter the Value of 2 Element : Cherry
Please enter the Value of 3 Element : Kiwi
Please enter the Value of 4 Element : Banana
Before Clear() - List =  ['Dragon', 'Cherry', 'Kiwi', 'Banana']
After Clear()  - List =  []

NOTE: You can also use this clear function on Mixed Lists and Nested Lists.