A queue in a ring
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.
push finds the back slot: tail = (head + size) % 8. With head at 0 that gives slots 0, 1 and 2 for A, B and C. Each push writes one slot and adds 1 to size: one step, however long the queue is.
pop returns the item in slot head, then moves head on by one. A and B leave; head goes 0, 1, 2. Nothing else moves: C stays in slot 2. A list's pop(0) would shift every item left instead.
Wrapping around
Push D, E, F, G and H. They land in slots 3 to 7, the last slots of the list. Now head is 2 and size is 6, so the queue holds C to H, front to back.
Push I: tail = (2 + 6) % 8 = 0. The % gives the remainder after dividing, so 8 becomes 0 and I goes back to slot 0, which A left free. The end of the list joins its start: a ring.
Push J into slot 1. Now size is 8 and tail = (2 + 8) % 8 = 2, the same slot as head. head and tail also meet when the queue is empty, so size is what tells full from empty.
Push K finds size == CAP and raises an error instead of writing over C, the front item. A growing queue would copy all 8 items into a list twice as big; a bounded deque drops the oldest item instead.
Both ends
Pop six times: C, D, E, F, G and H come out. head counts 3, 4, 5, 6, 7, then (7 + 1) % 8 = 0. Now the front is I in slot 0, with J behind it.
A deque (a double-ended queue) can also add at the front: head = (head - 1) % 8. In Python -1 % 8 is 7, so Z goes into slot 7, just before I. Both ends take one step.
You rarely write this by hand: collections.deque has append, appendleft, pop and popleft, each O(1). Inside CPython it is a chain of 64-slot blocks rather than one ring, but the idea is the same: the ends move, the items stay.
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.