There is a big list l, which operation is faster

a=l.pop() 

or

 a=l[-1] l=l[:-1] 
  • 3
    And why not measure? - Qwertiy
  • 3
    Take, yes, measure, what is the difficulty then? - Chp
  • pop from the beginning of the list and from the end, will be very different in time - vadim vaduxa

2 answers 2

According to the python wiki TimeComplexity, the slice for the k-th element is carried out by O (k) on average.

 l = ['a', 1, b'byte'] id(l) 58706920 id(l[:-1]) 58368248 

As a result, the slice creates a new object with the desired range.

About how the list is arranged from the inside I suggest reading here Python list implementation

briefly, the pop () operation:

  • returns the element referenced by the last element in the array
  • the index of the last element is updated (size - = 1)
  • and if current_size <allocated_size / 2 then shrink (narrowing) of allocated memory occurs

this gives us the opportunity to take the complexity of the pop () operation in O (1) "average".

pop () does not create a new object:

 l = ['a', 1, b'byte'] id(l) 58908424 l.pop() b'byte' id(l) 58908424 

RESPONSE pop () operation faster.

    For example: You can measure it like this:

     import time class Profiler(object): def __enter__(self): self._startTime = time.time() def __exit__(self, type, value, traceback): print("Elapsed time: {:.20f} sec".format(time.time() - self._startTime)) with Profiler() as pop: a=l.pop() with Profiler() as pop2: a=l[-1] l=l[:-1]