With the list: [-1, 0, 43, 128, 32]
, there are a couple ways of removing the final element.
list.pop()
list = list[:-1]
(not recommended?)del list[-1]
They would all return [-1, 0, 43, 128]
, but what's least computationally intensive and does it make a difference? I'm aware of modules like timeit
which I could use to test this for myself. But I'm wary of uncontrolled variables and my non-expertise could definitely dilute the results. As well, does the best option differ for strings, or floats, or booleans? What about multidimensional lists?
I'm not quite sure how to control and test these variables, so I'd figure I'd ask here to see if there is a general hierarchy.
That question explains the differences between methods of deletion, but does not address slicing. It also does not address speed at all. The accepted answer makes vague mentions to efficiency which I can see being part of the solution, but I do not see how it fits with slicing.
As per mentioned in the Python wiki. Time complexities are as follows:
O(1)
O(n)
O(k+n)
import time
all_t = 0.
for i in range(1000):
list_ = [i for i in range(100000)]
start_ = time.time()
list_.pop()
all_t += time.time() - start_
print("Average Time for POP is {}".format(all_t/1000.))
all_t = 0.
for i in range(1000):
list_ = [i for i in range(100000)]
start_ = time.time()
del list_[-1]
all_t += time.time() - start_
print("Average Time for DEL is {}".format(all_t/1000.))
all_t = 0.
for i in range(1000):
list_ = [i for i in range(100000)]
start_ = time.time()
list_ = list_[:-1]
all_t += time.time() - start_
print("Average Time for SLICE is {}".format(all_t/1000.))
Average Time for POP is 7.793903350830078e-07
Average Time for DEL is 9.80854034423828e-07
Average Time for SLICE is 0.0006206443309783935
pop()
is the fastest when you do not specify an index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With