Python queues with deque
Process work in first-in, first-out order.
Python
from collections import deque
queue = deque(["A", "B"])
queue.append("C")
print(queue.popleft())
print(queue.popleft())
print(list(queue))
assert queue.popleft() == "C"
assert not queueOutput
A B ['C']
Explanation
A queue removes the oldest item first. deque supports efficient additions and removals at either end; append plus popleft implements a FIFO queue.
Removing index zero from a list shifts remaining items. A deque avoids that repeated shifting for queue operations.
Explore the dry run
Guided walkthroughReady
1
from collections import deque2
3
queue = deque(["A", "B"])4
queue.append("C")5
print(queue.popleft())6
print(queue.popleft())7
print(list(queue))8
assert queue.popleft() == "C"9
assert not queueFollow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| A arrived before B. | front -> A, B <- back | — | |
| Add C at the back. | front -> A, B, C <- back | — | |
| Remove and print the oldest item, A. | queue = ['B', 'C'] | A | |
| Remove and print the next oldest item, B. | queue = ['C'] | A B | |
| Display the remaining queue. | queue = ['C'] | A B ['C'] | |
| Remove the final item. | queue = [] | A B ['C'] | |
| Verify emptiness before any further removal. | queue = [] | A B ['C'] |
Cost and common mistakes
O(1) deque append and popleft; displaying all remaining items is O(n). Storage is O(n).
- popleft on an empty deque raises IndexError.
- This sample is a single-threaded queue; concurrent producer/consumer coordination is a separate concern.
Try it yourself
Append D before the final removal. What remains after removing C?
Reveal answer and reasoning
The queue contains D, so the final emptiness assertion would need to change.