Python List clear() Method (original) (raw)

Last Updated : 18 Dec, 2024

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)

`

Table of Content

**Syntax of clear() Method

**list.clear()

**Parameters:

**Return Type:

**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)

`

Explanation:

**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)

`

Explanation:

**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)

`

Explanation:

**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)

`

**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)

`