1stack = ["A", "B"]2stack.append("C")3stack.pop() # the top4from collections import deque5q = deque(["A", "B"])6q.append("C")7q.popleft() # the frontlisttopstackfrontbackABCABCABC0 moves
Code card: the program; the highlighted line is the one runningStack holder: blocks go on and come off at the topQueue conveyor: blocks join at the back, leave from the frontList tray (step 9 only): a plain list doing pop(0)Letter blocks: the items, "A", "B" and "C"Each step highlights one line of the program. On the stack, blocks enter and leave only at the top: "C", pushed last, is popped first (LIFO). On the queue, blocks join at the back and leave from the front: "A", enqueued first, is dequeued first (FIFO). For list.pop(0), a separate list tray behind the queue shows the work a list has to do: after "A" leaves, "B" and "C" slide forward one place each. The deque on the conveyor is not touched, and deque.popleft() moves nothing else. The drawing keeps each queue item in its own slot. A Python deque really works like that: it is a chain of fixed-size blocks with a moving front, so popleft() never shifts the other items. A list is one packed row, which is why list.pop(0) has to shift them.

Stacks: last in, first out

  1. A stack is a pile where you only touch the top, like a pile of plates. Line 1 makes one with a Python list: "A" goes in first, at the bottom, then "B" on top of it.

Queues: first in, first out

Picking the tool

Try it in the Python prompt

;; step 1/10 · line 1: stack = ["A", "B"]
>>> stack = ["A", "B"]
>>> stack
['A', 'B']
>>> stack[-1]     # the top: the last item
'B'

The drawing keeps each queue item in its own slot. A Python deque really works like that: it is a chain of fixed-size blocks with a moving front, so popleft() never shifts the other items. A list is one packed row, which is why list.pop(0) has to shift them. O(n) ("order n") means the work grows in step with the number of items n; O(1) means it stays about the same however many items there are.