简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM