Stack and queue
A stack is last-in, first-out. A queue is first-in, first-out. In Python a list is a stack; collections.deque is a queue (and a stack). The queue module adds thread-safe variants.
Detailed Explanation
These are access patterns, not separate builtins. A stack pushes and pops on one end. DFS, undo history, and the interpreter's call stack are stacks. A list is enough: append to push, pop() to pop, stack[-1] to peek. All three are O(1). pop(0) is not a stack operation and is O(n).
A queue enqueues at one end and dequeues at the other. BFS, task workers, and request buffers are queues. deque.append plus deque.popleft is O(1) on both ends. A list used as a queue with pop(0) works on ten items and dies on ten thousand.
queue.Queue, LifoQueue, and PriorityQueue wrap these patterns with locks, blocking get/put, and a task_done / join protocol for thread pools. Use them when producers and consumers run in different threads. Use asyncio.Queue when they are tasks on one event loop. Do not use queue.Queue inside async code; it blocks the loop.
A double-ended queue (deque) can act as either, or as a sliding window. A priority queue is a heap: you pop the smallest priority, not the oldest item. heapq is the in-thread priority queue.
Choose by the question you pop. Oldest work: queue. Newest work: stack. Most important work: heap. If you need random access, you want a list or a dict, not a stack or queue that you keep converting.
Code Examples
# Stack: undo history.
undo: list[str] = []
undo.append("type A")
undo.append("type B")
print(undo.pop()) # type B
print(undo[-1]) # type A peekfrom collections import deque
# Queue: incoming jobs.
jobs: deque[str] = deque()
jobs.append("resize")
jobs.append("upload")
print(jobs.popleft()) # resizefrom queue import Queue
# Threads: blocking queue.
pending: Queue[str] = Queue()
pending.put("resize")
print(pending.get()) # resize
pending.task_done()Common Gotchas
`list.pop(0)` as a queue is O(n)
use `deque.popleft`.
`queue.Queue.get()` blocks the event loop
in asyncio use `asyncio.Queue`.
A list used from two threads is not a queue
append and pop can interleave. Use `queue.Queue`.
`LifoQueue` is a thread-safe stack
the name is the access order, not a different data structure family.