Sunday, November 17, 2024
Google search engine
HomeLanguagesPython List clear() Method

Python List clear() Method

Python List clear() method is used for removing all items from the List. It does not require any parameter. It clears the list completely and it does not return anything.

Example :

Python3




lis = [1, 2, 3]
lis.clear()
print(lis)


Output :

[]

Python list clear() Method Syntax

Syntax: list.clear()

Parameters: The clear() method doesn’t take any parameters

Returns: list clear() method doesn’t return any value.

List clear() Methods in Python Examples

Empty a List using clear() Method

In this example, we are creating a list, and we print it before clearing and after clearing in Python.

Python3




# Python program to clear a list
# using clear() method
 
# Creating list
GEEK = [6, 0, 4, 1]
print('GEEK before clear:', GEEK)
 
# Clearing list
GEEK.clear()
print('GEEK after clear:', GEEK)


Output:

GEEK before clear: [6, 0, 4, 1]
GEEK after clear: []

Emptying the List Using del

In this example, we are creating a 2D list, and we are using the del keyword to delete the list data.

Python3




my_list = [1, 2, 3, 4, 5]
del my_list[:]
print(my_list)


Output :

[]

Clearing 2D list using list clear() Method

In this example, we are creating a 2D list, and we are clearing the list at all indexes of the 2d list and printing it.

Python3




# Defining a 2-d list
lis = [[0, 0, 1],
       [0, 1, 0],
       [0, 1, 1]]
 
# clearing the list
lis.clear()
 
print(lis)


Output:

[]

Clearing 2D list with specific index using list clear() Method

In this example, we are creating a 2D list, and we are clearing the list at the first index of the 2d list and printing it.

Python3




# Defining a 2-d list
lis = [[0, 0, 1],
       [0, 1, 0],
       [0, 1, 1]]
 
# clearing the list
lis[0].clear()
 
print(lis)


Output:

[[], [0, 1, 0], [0, 1, 1]]

Using del Keyword vs list clear() Method

We can use the del keyword to delete the slice of a list from memory. But while using the list.clear() Method, it modifies the list inplace by removing all elements of the list. Nevertheless, the output from both approaches is the same.

Python3




lis_1 = [1, 3, 5]
 
lis_2 = [7, 9, 11]
 
# using clear method
lis_1.clear()
print("List after using clear():", lis_1)
 
# using del to clear items
del lis_2[:]
print("List after using del:", lis_2)


Output:

List after using clear(): []
List after using del: []

Note: We are not directly using del lis_2, since it’ll delete the list object, but we want to delete the contents of the list, so we are deleting the slice of the list representing the complete list.

RELATED ARTICLES

Most Popular

Recent Comments