Open In App

Python List clear() Method

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

clear() method in Python is used to remove all elements from a list, effectively making it an empty list. This method does not delete the list itself but clears its content. It is a simple and efficient way to reset a list without reassigning it to a new empty list.

Example:

Python
a = [1, 2, 3]

# Clear all elements from the list 'a'
a.clear()
print(a)

Output
[]
  • Here, the clear() method removes all the elements from the numbers list, leaving it empty.

Syntax of clear() Method

list.clear()

Parameters:

  • The clear() method does not take any parameters.

Return Type:

  • It modifies the original list and does not return any value (None).

Examples of clear() Method

1. Clearing a list of strings

clear() method can be used to remove all elements from a list of strings, leaving it empty. This is helpful when we want to reuse the list later without creating a new reference.

Python
a = ["Geeks", "for", "Geeks"]

# Clear all elements from the list 'a'
a.clear()
print(a)  

Output
[]

Explanation:

  • The clear() method empties the words list while keeping the variable words intact.

2. Clearing a nested list:

When working with a list that contains other lists (nested lists), calling clear() on the parent list removes all the inner lists as well, effectively clearing the entire structure but keeping the reference to the parent list intact.

Python
a = [[1, 2], [3, 4], [5, 6]]

# Clear all elements from the list 'a'
a.clear()
print(a) 

Output
[]

Explanation:

  • Even if the list contains sublists, the clear() method removes all elements, including nested ones.

3. Resetting a list without deleting its reference

By using clear(), we can empty a list without creating a new list or breaking any references to it. This is useful when we want to clear the contents of a list while keeping the variable name and its references intact for future use.

Python
a = [10, 20, 30]

# Clear all elements from the list 'a'
a.clear()
print(a)  

Output
[]

Explanation:

  • This is useful when we want to reset the content of a list but still use the same variable later in the program.

Practical Applications of clear() Method

1. Reusing a List:

clear() method allows us to empty a list without creating a new one, making it easy to reuse the same list for storing new data.

Python
a = [10, 20, 30]

# Clear all elements from the list 'a'
a.clear()
a.append(40)
print(a) 

Output
[40]

2. Memory Optimization:

Using clear() helps in releasing the memory held by the elements of the list, making it available for other operations without creating a new list object.

Python
a = [i for i in range(1_000_000)]

# Clear all elements from the list 'a'
a.clear()
print(a)  

Output
[]


Next Article

Similar Reads