Using the clear() Function to Remove All Values in a List
In Python, the clear()
function is used to initialize a list or remove all elements from a list at once, leaving it empty.
The clear()
function removes all elements in the list but does not delete the list itself.
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 the function call, my_list
is empty, but the list itself remains intact.
The clear()
method is useful when you need to quickly empty a large list or when you want to reuse a defined list.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.