Keep the top at the end of the list, because the front costs O(n) per push or pop
A list keeps its items side by side. Taking the last one moves nothing else. Taking the first one shifts every item behind it down one place:
pop() pop(0) Red leaves. pop() moves nothing else. pop(0) moves the 4 orange items behind it one place each.
Here are n pushes, then n pops, at each end:
def fill_end(n):
stack = []
for i in range(n):
stack.append(i)
def drain_end(n):
stack = list(range(n))
while stack:
stack.pop()
def fill_front(n):
stack = []
for i in range(n):
stack.insert(0, i)
def drain_front(n):
stack = list(range(n))
while stack:
stack.pop(0)
Timed:
n times each, in ms:
| n | At the end: push, pop | At the front: push, pop |
|---|---|---|
| 10,000 | 0.18, 0.25 | 7.29, 5.99 |
| 20,000 | 0.34, 0.48 | 30.70, 26.31 |
| 40,000 | 0.69, 0.97 | 136.68, 124.81 |
| 80,000 | 1.45, 2.09 | 560.13, 514.67 |
At the end the calls are append and pop(), and at the front insert(0, x) and pop(0).
Python 3.12, best of 5 runs with timeit, on the laptop these numbers come from.
Double n and the end's time doubles. That's O(1) per operation. For append it's amortized O(1), in the same sense as a dict's insert in the hash-maps lesson: now and then the list grows, and that rare cost spreads over all the appends.
Double n and the front's time grows about four times. That's O(n) per operation, and O(n²) for all of them. Either way the list takes O(n) memory for n items.
The table counts milliseconds. In the editor, write moves(n, front) to count the work behind them: how many times an item shifts one place when you pop all n items, from the front or from the end.