10

Shouldn't they both be O(1), as popping an element from any location in a Python list involves destroying that list and creating one at a new memory location?

Mike Müller
  • 77,540
  • 18
  • 155
  • 159
Teererai Marange
  • 1,942
  • 4
  • 29
  • 48

2 Answers2

27

Python's list implementation uses a dynamically resized C array under the hood, removing elements usually requires you to move elements following after up to prevent gaps.

list.pop() with no arguments removes the last element. Accessing that element can be done in constant time. There are no elements following so nothing needs to be shifted.

list.pop(0) removes the first element. All remaining elements have to be shifted up one step, so that takes O(n) linear time.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
10

To add to Martijn's answer, if you want a datastructure that has constant time pops at both ends, look at collections.deque.

Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842