1def push(q, x):2 if q.size == CAP:3 raise IndexError("full")4 tail = (q.head + q.size) % CAP5 q.buf[tail] = x6 q.size += 17def pop(q):8 x = q.buf[q.head]9 q.buf[q.head] = None10 q.head = (q.head + 1) % CAP11 q.size -= 112 return x0127% 83654q.head0q.size0xABCDEFGHIJKZheadtail
Slots 0 to 7: one Python list, laid out as a loopLetter blocks: the items in the queueFlags: head (front item) and tail (next free slot)A queue kept in a Python list of 8 slots, drawn as a loop so that slot 7 sits next to slot 0. Push writes slot (head + size) % 8; pop reads slot head and moves head on by one. The flags mark head and tail; no letter ever shifts. When tail reaches the end it wraps to 0, and a deque can also step head backwards: (0 - 1) % 8 = 7.

A queue in a ring

  1. A queue adds at the back and takes from the front. Here it lives in a plain Python list of 8 slots, numbered 0 to 7. q.head is the slot of the front item; q.size counts the items. Both start at 0.

Wrapping around

Both ends

What happens

;; step 1/10 · slots
setup (runs before the card):
  from types import SimpleNamespace
  CAP = 8
  q = SimpleNamespace(buf=[None] * CAP, head=0, size=0)


slots 0:· 1:· 2:· 3:· 4:· 5:· 6:· 7:·
head = 0  size = 0  tail = (0 + 0) % 8 = 0

The card's functions run as-is after three lines of setup: from types import SimpleNamespace; CAP = 8; q = SimpleNamespace(buf=[None] * CAP, head=0, size=0). push_front, used in step 9, is shown in that step's notes. To keep the card short, pop has no empty check. Real code starts pop with if q.size == 0: raise IndexError("empty"), which is what deque.pop does on an empty deque.