A first-in-first-out queue removes the oldest enqueued item first. Python's collections.deque supports appending at the right and removing from the left without shifting the entire collection. Those endpoint operations are O(1) in the intended queue use. A queue decides order; it does not provide durable delivery, retries, consumer acknowledgment, or fairness among external workers. A bound on queue length and a behavior when full matter in a live service, because constant-time insertion does not prevent unbounded memory growth when producers outrun consumers.
Queues: preserve arrival order without front shifts
Operational case
A loading dock receives pallets P-47, P-52, and P-61. The next pickup is P-47, and P-61 remains waiting. Using a list with pop(0) would shift later entries on each pickup, which becomes expensive for a large backlog. A deque keeps the endpoint contract clear. If P-47's pickup fails after it has been removed, this in-memory queue alone cannot know whether to retry safely; the application needs a separate receipt and retry policy.
Working Python program
from collections import deque
waiting_pallets = deque(["P-47", "P-52", "P-61"])
next_pickup = waiting_pallets.popleft()
print(next_pickup)
print(list(waiting_pallets))Output
P-47
['P-52', 'P-61']Time, space, and tradeoff
Enqueue and dequeue at opposite ends are O(1), while scanning the queue for a specific pallet is O(n). Space is O(n) for n waiting items. A deque is often the right in-process choice; a distributed queue has different guarantees about persistence, visibility, and duplicate delivery. Set backpressure or a maximum backlog before production use, and define whether an empty dequeue raises or returns a sentinel so callers do not mistake no work for a valid item.
Common Mistakes
- Do not use list.pop(0) for a large FIFO backlog.
- Do not mistake an in-memory deque for durable messaging.
- Do not let the queue grow without a capacity or backpressure rule.
Connected lessons
- Stacks and Queues
- DSA Tutorial
- Stacks: last-in-first-out for reversible edits
- Ring buffers: make capacity and overwrite rules explicit
- Graphs: adjacency lists and breadth-first reachability
- Project: choose structures for a dispatch board
- Project: audit depot connectivity and daily ranges
- Linear and hash structure decisions
Two-stack window aggregation: keep FIFO order under a monoid adds a distinct structure contract to compare.
Persistent two-list queues: fork FIFO dispatch history adds a distinct structure contract to compare.
