Python List clear() Function
The List clear()
method removes all items from the list, making it an empty list.
Syntax
my_list.clear()
clear() Parameters
Python List clear()
function does not take any parameters.
clear() Return Value
Python List clear()
function does not return any value: it empties the list in place.
Examples
Example 1: Empty a List with clear()
my_list = ['Tom', 'David', 'Anna']
my_list.clear()
print(my_list) # Output: []
output
[]
Example 2: clear() vs Assigning an Empty List
clear()
is not same as assigning an empty list my_list = []
.
Assigning an empty list to my_list
with my_list = []
does not clear the list in-place because it essentially replaces the my_list
variable with a new, empty list. This means that if there were other references to the original list, those references remain unchanged, potentially leading to issues.
In the following example you can see an example of assigning a new empty list instead of clearing with clear()
method:
# Original list
original_list = [1, 2, 3]
# Another reference to the original list
another_reference = original_list
# Attempt to clear the list using assignment
original_list = []
# Print the original list and the other reference
print("Original list after clearing:", original_list)
print("Another reference after clearing:", another_reference)
output
Original list after clearing: []
Another reference after clearing: [1, 2, 3]
Alternative to clear() method for Python 2 or below Python 3.2 users
For Python 2.x or below Python 3.2 users, clear()
method is not available.
Alternative 1: del keyword
You can remove all items from the list by using del keyword on a start-to-end slice.
my_list = ['Tom', 'David', 'Anna']
del my_list[:]
print(my_list) # Output: []
output
[]
Alternative 2: Assign Empty List
Assigning empty list to a start-to-end slice will have same effect as clear()
.
my_list = ['Tom', 'David', 'Anna']
my_list[:] = []
print(my_list) # Output: []
output
[]
Alternative 3: Multiplying 0 to a List
Multiplying 0 to a list using multiplication assignment operator will remove all items from the list in place.
my_list = ['Tom', 'David', 'Anna']
my_list *= 0
print(my_list) # Output: []
output
[]
Any integer that is less than or equal to 0 would have the same effect.