Sub topic 2
A first queue on a Python list and why pop(0) is slow
This chapter assumes you know basic Python syntax, functions, classes, list indexing, and Big-O notation for common operations. You should also know what a queue is: a first-in, first-out (FIFO) structure with enqueue, dequeue, peek, and size operations. Here you build a queue on a Python list, measure where it goes wrong, and see why later chapters introduce better designs.
The simplest queue
A Python list already has the two operations a queue needs. append adds an item at the back, and pop(0) removes the item at the front.
items = ["a", "b", "c"]
items.append("d") # enqueue at the back: amortized O(1)
first = items.pop(0) # dequeue from the front: O(n), every remaining item shifts left
print(first, items) # a ['b', 'c', 'd']The output is a ['b', 'c', 'd']. The item that entered first, "a", left first, so the FIFO rule holds. The code is correct. The problem is cost.
Why enqueue is cheap
A list stores its items in one contiguous block of memory. When you call append, Python writes the new item just after the last one. If the block is full, Python allocates a larger block and copies the items over. It over-allocates each time, so the copy happens rarely. Averaged over many calls, each append takes constant time. This is called amortized O(1).
Why dequeue is expensive
pop(0) removes the first slot. Because the list must stay contiguous and indexed from 0, every remaining item has to move one slot to the left. With n items, that is n - 1 moves, so the cost is O(n).
For a queue of 4 items this is invisible. For a queue of a million items, each dequeue moves about a million references. Draining the whole queue costs O(n²) in total.
Wrapping it in a class
A queue class hides the list and exposes only the queue operations.
class ListQueue:
def __init__(self):
self._items = []
def __len__(self):
return len(self._items)
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if not self._items:
raise IndexError("dequeue from empty queue")
return self._items.pop(0)
def peek(self):
if not self._items:
raise IndexError("peek at empty queue")
return self._items[0]
q = ListQueue()
for name in ["ann", "bo", "cy"]:
q.enqueue(name)
print(q.dequeue(), q.peek(), len(q)) # ann bo 2Only dequeue is slow. peek reads _items[0] in O(1), len is O(1), and enqueue is amortized O(1).
Measuring the problem
You can see the cost with timeit. The script below drains lists of growing size with pop(0). If the cost per pop were constant, doubling the size would double the time. Instead the time grows roughly fourfold.
import timeit
def drain(n):
items = list(range(n))
while items:
items.pop(0)
for n in (10_000, 20_000, 40_000):
t = timeit.timeit(lambda: drain(n), number=1)
print(f"n={n:>6} {t:.3f} s")Exact times depend on your machine. The trend is what matters: each doubling of n raises the total time by about four, which is the signature of O(n²).
Common mistakes
- Using
pop()instead ofpop(0).pop()with no argument removes the last item, which gives you a stack (last in, first out), not a queue. - Using
insert(0, x)pluspop(). This reverses the roles, with the same problem:insert(0, x)is O(n) because it shifts every item right. - Using
del items[0]or slicing.del items[0]has the same O(n) shift.items = items[1:]is worse, because it copies the whole list on every dequeue. - Tracking a head index and never deleting. Some people keep an integer
headand just advance it. Dequeue becomes O(1), but the list never shrinks, so memory grows with every item ever enqueued. Fixing that leads naturally to the circular buffer covered later.
What comes next
The slowness comes from one design choice: the front of the queue is always slot 0. If the front could move, nothing would have to shift. The next chapters take two routes to that goal. A linked-node queue keeps pointers to both ends. A circular buffer keeps a moving head index in a fixed array. Both make dequeue O(1).
Exercise
A queue is built on a list with append for enqueue and pop(0) for dequeue. You enqueue 100,000 items and then dequeue them all. Roughly how does the total dequeue cost compare with doing the same for 200,000 items, and why?
Show answer
Draining 200,000 items takes about four times as long. Each pop(0) shifts all remaining items, so one drain does about n²/2 moves in total, which is O(n²). Doubling n multiplies the work by about 4, not 2.
Exercise
Which operation of the ListQueue class is O(n), and which two changes of data structure would remove that cost?
Show answer
dequeue is O(n) because pop(0) shifts every remaining item. A linked-node queue with head and tail pointers, or a circular buffer with a moving head index, makes it O(1).