Lecture

Using the clear() Function to Remove All Values in a List

In Python, the clear() method is used to remove all elements from a list, leaving it empty but still defined.

This method does not delete the list itself—only its contents.

Example Usage of clear() Function
my_list = [1, 2, 3, 4, 5] # Output: [1, 2, 3, 4, 5] print("my_list:", my_list) # Remove all elements from the list my_list.clear() # Output: [] print("my_list:", my_list)

In the code above, the clear() function is used to remove all elements from my_list.

After calling clear(), my_list becomes an empty list ([]), but the list object still exists in memory and can be reused.

The clear() method is useful when you need to quickly empty a large list or when you want to reuse a defined list.

Quiz
0 / 1

The clear() method removes all elements of the list and also deletes the list itself.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result