Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to remove last element of list?

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]
  • And probably a couple more...

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.

Not a Duplicate of Difference between del, remove and pop on lists

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.

like image 663
CtrlAltF2 Avatar asked Jun 02 '19 21:06

CtrlAltF2


1 Answers

As per mentioned in the Python wiki. Time complexities are as follows:

  • Pop last O(1)
  • Delete Item O(n)
  • Set Slice O(k+n)

Experimental Study

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.))

Results

Average Time for POP is 7.793903350830078e-07
Average Time for DEL is 9.80854034423828e-07
Average Time for SLICE is 0.0006206443309783935

Summary

pop() is the fastest when you do not specify an index.

like image 199
Yahya Avatar answered Nov 14 '22 07:11

Yahya