Python · Course navigation

Python queues with deque

Process work in first-in, first-out order.

On this page
Before you start

Collections and method calls.

  • Process work in first-in, first-out order.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

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 queue
Output
A
B
['C']

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1from collections import deque
2
3queue = deque(["A", "B"])
4queue.append("C")
5print(queue.popleft())
6print(queue.popleft())
7print(list(queue))
8assert queue.popleft() == "C"
9assert not queue

Follow 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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']

Behind the scenes

How Python processes this code

Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.

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.

Further reading