Problem scenario
You use del and pop to remove items from lists. You noticed that pop
is slower than del
. Why is this the case?
Solution
There are two reasons. One, pop returns the value that is removed. Two, pop acts as a function call as opposed to a primitive action. Whereas the del invokes a primitive action (a non-recursive function call), pop involves recursion.
Basically, another operation has to take place with pop
compared to del
.
This program will have three function calls. If you run this program, you will see the number of function calls because we import cProfile
and use it:
import cProfile
a = 1, 2, 3, 4, 5
contintlist = list(a)
cProfile.run('del contintlist[3]')
This program will have four function calls:
import cProfile
a = 1, 2, 3, 4, 5
contintlist = list(a)
cProfile.run('contintlist.pop(3)')
You can run the above programs to see for yourself.
This program prints out "4":
a = 1, 2, 3, 4, 5
contintlist = list(a)
x = contintlist.pop(3)
print(x)
This next program is very similar, but it does not run:
a = 1, 2, 3, 4, 5
contintlist = list(a)
x = del contintlist[3]
print(x)
This program will print out something like this:
File "t.py", line 3
x = del contintlist[3]
^
SyntaxError: invalid syntax
You see that pop does a return
which is an additional function (as the profiler output of the first two programs will show). The del
invocation is faster, but it returns nothing.