3/36
Part 1 of 8 · Last in, first outLearn and do

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:

Taking an item out of a list
pop()
abcde
pop(0)
abcde

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:

nAt the end: push, popAt the front: push, pop
10,0000.18, 0.257.29, 5.99
20,0000.34, 0.4830.70, 26.31
40,0000.69, 0.97136.68, 124.81
80,0001.45, 2.09560.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.