Speed of del vs remove on list
Question:
Assume that I have a list, and I have an element that I want to remove from it. Now suppose I have the index of that element, and I also know exactly what element it is. Would it be faster to do del myList[index]
or myList.remove(element)
?
Answers:
If you know the index already, you’d use del
.
Otherwise, remove
first needs to traverse the list, find the (first) index for the element, then del
it. This would, therefore, make it slower.
Without any knowledge on how del
or remove()
performs, we can write a test using the timeit
library to determine which one is faster. In this example, I simulate using both methods 10,000 times and print the average time required:
import timeit
num_runs = 10000
del_method = 'lst = [1, 2, 3]; del lst[i]'
del_setup = 'i = 0'
print(timeit.Timer(del_method, setup=del_setup).timeit(number=num_runs))
remove_method = 'lst = [1, 2, 3]; lst.remove(ele)'
remove_setup = 'ele = 1'
print(timeit.Timer(remove_method, setup=remove_setup).timeit(number=num_runs))
Ouput:
0.0005947000000000036
0.0007260000000000044
As we can see, del
performs faster in this simple scenario. This makes sense knowing that remove()
performs a search before removing the element. I can imagine with an even larger list the difference between the times would only grow.
Short answer: del
is remarkably faster than remove
.
Assume that I have a list, and I have an element that I want to remove from it. Now suppose I have the index of that element, and I also know exactly what element it is. Would it be faster to do del myList[index]
or myList.remove(element)
?
If you know the index already, you’d use del
.
Otherwise, remove
first needs to traverse the list, find the (first) index for the element, then del
it. This would, therefore, make it slower.
Without any knowledge on how del
or remove()
performs, we can write a test using the timeit
library to determine which one is faster. In this example, I simulate using both methods 10,000 times and print the average time required:
import timeit
num_runs = 10000
del_method = 'lst = [1, 2, 3]; del lst[i]'
del_setup = 'i = 0'
print(timeit.Timer(del_method, setup=del_setup).timeit(number=num_runs))
remove_method = 'lst = [1, 2, 3]; lst.remove(ele)'
remove_setup = 'ele = 1'
print(timeit.Timer(remove_method, setup=remove_setup).timeit(number=num_runs))
Ouput:
0.0005947000000000036
0.0007260000000000044
As we can see, del
performs faster in this simple scenario. This makes sense knowing that remove()
performs a search before removing the element. I can imagine with an even larger list the difference between the times would only grow.
Short answer: del
is remarkably faster than remove
.