4. Queue
Opening
Big idea: Fair service often means completing the oldest waiting request first.
Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.
- Explain FIFO and distinguish a queue from a stack.
- Implement queue operations and handle the empty case.
- Use a deque when both ends need access.
Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.
This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.
The previous chapter stored work in a pile. Only the top item could be reached. This chapter stores work in a line. Only the ends have defined roles.
The chapter builds in stages. First the waiting-line rule and its operation names.
Then a plain list implementation. Then a circular store that reuses space.
Then the deque, which opens both ends. Each stage reuses the previous one.
Study by tracing. Cover the expected output and predict it first. When a prediction fails, find the first line where your trace diverged. That line holds the lesson.
The last chapter ended with a pile of plates: only the top plate could move. This chapter starts with a bus line: newcomers join at the back and the person at the front boards first.
Hold both pictures side by side as you read, because every section compares them.
Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.
4.1 INTRODUCTION TO QUEUE
A queue models work arriving over time. New work joins the rear. Service removes from the front. A job that has already been waiting is not pushed behind every new arrival.
First in, first out is a service rule. It is different from choosing the shortest job or the most urgent job. Those choices can be useful too, but they describe different scheduling policies.
- Write incoming tags in their arrival order.
- Add new tags at the rear.
- Remove the front tag and identify the next waiting tag.
Several documents reach a shared printer while it is busy. The oldest waiting job should normally be served first.
A queue is an abstract data structure with insertion at the rear and removal at the front. The rear is the end where new entries arrive. The front is the end where service happens.
A queue follows FIFO: first in, first out. Among entries still waiting, the earliest arrival is removed next. Later arrivals wait behind earlier ones. Position in the arrival history decides, not value or size.
First in, first out means the oldest waiting entry leaves next.
The printer spooler is the running example. Each arriving document joins a waiting line. The printer takes the oldest waiting document when it becomes free. A ticket counter and a bus line follow the same rule.
| Arrival order | Service order without interruptions |
|---|---|
| job A, job B, job C | job A, job B, job C |
Read the table. The left column lists arrivals from oldest to newest. The right column lists service in the same order. No later arrival overtakes an earlier one. That is the whole FIFO promise.
Write down what this program should print before you read the expected output.
line = []
line.append("token 1")
line.append("token 2")
line.append("token 3")
print(line.pop(0))
print(line)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 creates an empty line.
- Lines 2 to 4 append 3 tokens in order. Token 1 is the oldest.
- Line 5 removes the front with pop(0) and prints token 1.
- Line 6 shows the two newer tokens still waiting, in arrival order.
token 1
['token 2', 'token 3']Append "token 4" after line 4. Predict both printed lines.
Arrivals may continue while service continues. The next program serves twice with a new arrival in between. Watch how the newcomer waits its turn.
Try to predict the printed result first. The trace below explains every line.
line = ["job 1", "job 2"]
print(line.pop(0))
line.append("job 3")
print(line.pop(0))
print(line.pop(0))
print(line)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores two jobs with job 1 at the front.
- Line 2 serves job 1 and prints it.
- Line 3 is an arrival during service. Job 3 joins the rear.
- Line 4 serves job 2, the oldest waiter, and prints it.
- Line 5 serves job 3 and prints it.
- Line 6 prints the empty list. Every arrival was served exactly once.
job 1
job 2
job 3
[]Start with three jobs instead of two. Predict all five printed lines.
New arrivals never jump the line. Job 3 arrived while service continued, yet job 2 was still served before it. Waiting time depends on workload, but order depends only on arrival.
FIFO is a fairness rule, not a speed rule. A scheduler with deadlines may serve the nearest deadline first. That rule is not FIFO, even when a queue stores the jobs. Name the rule your task actually follows.
Tokens T1, T2 and T3 arrive in order. T1 is served. Then T4 arrives. Which token is served next, and why?
Goal. Name the next token served after one removal and one new arrival.
Approach. List the still-waiting tokens in arrival order.
Trace. T1 left, so T2, T3 and T4 wait. T2 arrived before T3 and T4.
Result. FIFO serves the oldest waiter, whatever arrived later.
Result: T2 is served next. Arrival order among the still-waiting tokens decides.
A list can act as anything: it allows reading and writing at every position. A queue is a discipline laid over storage.
Only the two ends have jobs, and each job belongs to exactly one end. That restriction is what makes behaviour predictable.
Compare this with the previous chapter. A stack adds and removes at one end, the top. A queue adds at the rear and removes at the front. One structure reverses history; the other preserves it.
| Question | Stack answer | Queue answer |
|---|---|---|
| Which entry is served next? | The newest remaining entry. | The oldest remaining entry. |
| Which ends are used? | One end, the top. | Two ends, rear and front. |
| Fits Undo? | Yes. Reversal is the goal. | No. It would undo the oldest first. |
| Fits a printer line? | No. New jobs would overtake old ones. | Yes. Arrival order is preserved. |
Read the table. Each row asks the same question of both structures. The first row is the decision rule. The second row names the working ends. The last two rows apply both structures to real tasks. Only the queue keeps printer order.
A queue is useful for print jobs, messages, buffered input and breadth-first exploration. A bus queue boards in arrival order so nobody is left behind.
A message buffer delivers texts in the order they arrived, so a reply still matches its question.
A real scheduling system may include priorities or cancellation. Those extra policies must be stated rather than assumed to be ordinary FIFO.
Read the diagram. Entries arrive in the first box and wait in the second. Service always happens in the third box, at the opposite end. The last box shows the new state: the next oldest waiter is now at the front.
Arrival order decides service order. Name the oldest waiter first, and the queue does the rest.
Why does using a stack for pending print jobs produce a different experience?
Goal. Explain what changes when print jobs wait in a stack instead of a queue.
Approach. Ask which waiting job each structure serves first.
Trace. A stack serves the newest waiting job. A stream of new arrivals can keep older work waiting. A queue serves the oldest waiter first.
Result. The stack reverses arrival order, while the queue preserves it.
Result: A plain queue preserves arrival order, while a stack reverses it.
4.2 OPERATIONS ON QUEUE
Queue errors often begin with a picture whose front and rear are not labelled. Choose the orientation first. Then enqueue and dequeue have unambiguous places to act.
Peek leaves the front where it is. Dequeue removes it. Size counts what remains after the change. If you trace only printed values and ignore state changes, these operations can look misleadingly similar.
- Draw the current queue and mark its front and rear.
- Apply the requested operation at its specified end.
- Record both the returned value and the new queue.
The operation names should make the waiting-line policy explicit.
Every queue operation needs a contract. The contract states the result. It also states the change to the waiting line. And it states the empty-queue behaviour.
| Operation | Contract |
|---|---|
| enqueue(x) | Add x at the rear. |
| dequeue() | Remove and return the front entry. |
| peek() | Return the front entry without removing it. |
| is_empty() | Return whether no entries are waiting. |
| size() | Return the number waiting. |
Read the table. Enqueue grows the rear. Dequeue shrinks the front and reports what it removed. Peek only observes. The last two operations only measure. Change and observation stay separate.
Enqueue grows the rear. Dequeue shrinks the front. Peek observes the front without change.
Predict the output before running this complete example.
queue = ["job A", "job B"]
queue.append("job C")
print(queue[0])
print(queue.pop(0))
print(queue)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The left-hand end is the front and the right-hand end is the rear.
- Append adds the new job behind earlier jobs.
- The indexed print only observes the front. Pop(0) then removes that entry.
job A
job A
['job B', 'job C']Add a job after the removal and predict the next job to be served.
Line 1 stores two jobs with job A at the front. Line 2 appends job C at the rear. Line 3 reads index 0, which is the peek idea: it prints job A and changes nothing.
Line 4 dequeues that same front entry. It prints job A again and removes it.
Line 5 shows job B at the front, followed by job C. ==The same printed value can hide a different effect.
== Only the final list exposes whether removal happened.
Before running the program, say the output in your own words.
queue = ["parcel A", "parcel B"]
print(queue[0])
print(len(queue))
print(queue.pop(0))
print(queue)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores 2 parcels with parcel A at the front.
- Line 2 peeks with index 0 and prints parcel A.
- Line 3 prints the size 2. Peeking changed nothing.
- Line 4 dequeues the same entry. It prints parcel A again, this time removing it.
- Line 5 shows one parcel left.
parcel A
2
parcel A
['parcel B']Replace line 2 with print(queue.pop(0)). Predict all four printed lines.
Removing or peeking when no entry exists is underflow. A fixed-capacity queue also needs a policy when full: refuse the new entry, wait, or use an explicitly documented alternative.
Silently discarding an old entry changes the behaviour.
Never dequeue or peek without knowing the queue is non-empty. An empty queue has no front to return.
Picture a counter with three chairs. A fourth visitor is refused politely or asked to wait.
The counter does not erase a seated visitor to make room. State the chosen behaviour in the interface, then implement exactly that.
Read the diagram. The first box asks for the front. The second box is the only question that matters: is anything waiting. An empty queue takes the third path and reports underflow. A non-empty queue takes the fourth path. The last box records the effect: exactly one entry left the line.
Write down what this program should print before you read the expected output.
queue = []
if queue:
print(queue.pop(0))
else:
print("empty: nobody is waiting")
queue.append("parcel C")
print(queue.pop(0))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 creates an empty queue.
- Line 2 tests the queue. An empty list counts as false.
- Lines 4 and 5 run instead. They report the empty state clearly.
- Line 6 adds one parcel.
- Line 7 serves it safely and prints parcel C.
empty: nobody is waiting
parcel CRemove line 6. Predict both printed lines.
The ticket counter below threads through the chapter. Tokens arrive, some are served, a new token arrives, and service continues. Follow the front after every step.
Try to predict the printed result first. The trace below explains every line.
served = []
waiting = ["T1", "T2", "T3"]
served.append(waiting.pop(0))
served.append(waiting.pop(0))
waiting.append("T4")
served.append(waiting.pop(0))
print(served)
print(waiting)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 and 2 set up an empty served record and 3 waiting tokens.
- Lines 3 and 4 serve T1, then T2. Each pop(0) removes the current front.
- Line 5 is a new arrival. T4 joins the rear behind T3.
- Line 6 serves T3. Service still follows arrival order.
- Lines 7 and 8 print the record: 3 tokens served in order, with 1 token still waiting.
['T1', 'T2', 'T3']
['T4']Serve once more after line 6. Predict both printed lists.
| Point in the program | Waiting | Served |
|---|---|---|
| Start | T1, T2, T3 | none |
| After two serves | T3 | T1, T2 |
| T4 arrives | T3, T4 | T1, T2 |
| After third serve | T4 | T1, T2, T3 |
Read the table. Each row freezes the program at one point. The middle column always keeps arrival order with the front on the left. New arrivals extend the right; service removes from the left. The served column only grows, in the same order.
To serve everything, loop while the queue is non-empty and dequeue inside. The loop condition itself is the emptiness test, so no separate guard is needed.
The final exercise practises exactly this shape with the token counter.
Peek supports decisions without commitment. A program can ask who is next before preparing resources.
The line stays unchanged while the program thinks. Size supports loops and progress reports: serving 3 of 10 tokens is a size reading, not a removal.
The is_empty test belongs beside every dequeue whose safety you cannot prove.
A printer queue holds job A, then job B. The program peeks, dequeues, then peeks again. What prints each time, and what remains?
Goal. Track printed values and contents across a peek, a removal and another peek.
Approach. Ask after every step whether the contents changed.
Trace. The first peek prints A and changes nothing. The dequeue prints A and removes it. The second peek prints B and keeps it.
Result. The prints are A, A and B. Only B remains.
Result: The prints are A, A and B. Peek observes twice; only the dequeue removes.
A program calls dequeue() twice on a one-entry queue. The second call crashes. What is the smallest repair?
Goal. Stop the crash while keeping every valid removal.
Approach. Ask which call meets an empty queue and what should happen there.
Trace. The first dequeue serves the only entry. The second dequeue has no front, so it raises. A guard before each uncertain dequeue takes the empty path instead.
Result. Test the queue before dequeuing, and report or skip the empty case deliberately.
Result: Guard each uncertain dequeue with an emptiness test. Report underflow instead of crashing.
4.3 IMPLEMENTATION OF QUEUE USING PYTHON
For a list-based queue, place the front on the left. Appending adds to the rear. Removing position zero serves the front. This gives a clear first implementation because the list order directly matches waiting order.
There is a cost hidden inside front removal: later list entries must shift. You can understand the queue rule first, then decide whether a different container is needed for a larger workload.
- Check that an item exists before removing it.
- Remove the front and leave all remaining entries in arrival order.
- Test mixed arrivals and removals, not just one initial batch.
A list makes the FIFO rule visible, even though its front-removal cost matters for large workloads.
Place the front on the left of a Python list. Appending adds at the rear. Removing position zero serves the front. Index zero peeks without change. This mapping keeps arrival order visible in the list order.
| Queue operation | List operation at the left and right ends |
|---|---|
| enqueue(x) | append(x) adds at the right end. |
| dequeue() | pop(0) removes from the left end. |
| peek() | Index 0 reads the left end. |
| is_empty() | The test not queue is true when empty. |
| size() | len(queue) counts the entries. |
Read the table. The right end is the rear and the left end is the front. Every row touches only its specified end. No row reaches into the middle. This single choice prevents rear-removal bugs.
Predict the output before running this complete example.
def enqueue(queue, item):
queue.append(item)
def dequeue(queue):
if not queue:
raise IndexError("empty queue")
return queue.pop(0)
def peek(queue):
if not queue:
raise IndexError("empty queue")
return queue[0]
queue = []
for tag in ["task A", "task B", "task C"]:
enqueue(queue, tag)
print(dequeue(queue))
print(peek(queue))
print(len(queue))Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Enqueue adds each incoming tag to the rear of the shared list.
- Dequeue checks that an entry exists before removing the front.
- Peek sees the new front after the removal. The size counts entries still waiting.
task A
task B
2Interleave an enqueue with each dequeue and keep a written record of the front and rear.
Lines 1 to 11 define three functions. Definitions alone change nothing. They wait for calls. Each function receives the queue it must change. The two guards raise a clear error for the empty case.
Lines 13 and 14 create an empty queue and enqueue three tasks in order. Task A is the oldest.
Line 15 dequeues and prints task A, removing it. Line 16 peeks and prints task B without removing it.
Line 17 prints 2: two tasks remain.
Definitions wait; calls act. Trace calls in order. The definitions only explain what each call will do.
Read the diagram. The first two boxes fix the ends: front on the left, rear on the right. The third box observes without change. The last box is the only operation that shrinks the list. Read the boxes before tracing any program.
The implementation mutates the supplied queue. Removing the first list entry requires later entries to shift, so list pop(0) is linear in the number of remaining entries.
That cost does not change the FIFO meaning, but it changes performance.
For a large practical queue, collections.deque provides efficient endpoint operations. For concurrent producers and consumers, synchronisation and waiting policies require more than this small teaching implementation.
Imagine a fixed row of four slots with a rear marker that only moves right. After serving the first two entries, one entry waits but the rear marker already stands at the end.
The store reports full although three slots stand free.
The wasted slots are not lost data. They are freed positions the markers cannot reach again. A linear fixed store forgets how to reuse them. The next section of this chapter fixes exactly that with wrap-around.
| Fixed linear store | Circular store | |
|---|---|---|
| Enqueue position | Moves right only, never returns. | Moves right and wraps to the start. |
| Slots freed by dequeue | Stay unreachable behind the front. | Are reused by wrapped markers. |
| False full | Possible while free slots exist. | Avoided by the wrap rule. |
| Empty test | No entries stored. | No entries stored, with markers reset or counted. |
Read the table. Each row compares the same question for both stores. The first two rows explain the waste and its repair. The third row names the symptom: false full. The last row shows what stays the same: emptiness still means nothing stored.
A circular queue keeps a fixed size but lets its markers wrap around. The rear steps forward with a remainder operation on the size. Freed slots re-enter circulation instead of piling up behind the front.
Work through the idea with a store of size 4. Slot indices run from 0 to 3. Stepping past slot 3 must return to slot 0. The remainder after division by the size computes exactly that return.
Before running the program, say the output in your own words.
size = 4
rear = 3
rear = (rear + 1) % size
print(rear)
front = 0
front = (front + 1) % size
print(front)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 fixes the store size at 4.
- Line 2 parks the rear at the last slot, index 3.
- Line 3 adds one step and wraps with the remainder operation. The rear returns to the start, index 0.
- Line 4 prints that wrapped rear.
- Lines 5 to 7 move the front from 0 to 1. No wrap is needed there yet.
0
1Start the rear at 2 instead. Predict the printed rear.
Read the diagram. The first two boxes are the enqueue half: write, then step with wrap. The next two boxes are the dequeue half: read, then step with wrap. The last box resolves the shared-marker puzzle: when front and rear coincide, the count tells full from empty.
The rear needs no separate marker in this design. Front plus count points at the next free slot, and the remainder keeps that sum inside the row.
One marker plus a count carries the same information as two markers, with less to keep consistent.
Write down what this program should print before you read the expected output.
class CircularQueue:
def __init__(self, size):
self.data = [None] * size
self.front = 0
self.count = 0
def enqueue(self, item):
if self.count == len(self.data):
raise IndexError("queue is full")
rear = (self.front + self.count) % len(self.data)
self.data[rear] = item
self.count += 1
def dequeue(self):
if self.count == 0:
raise IndexError("empty queue")
item = self.data[self.front]
self.front = (self.front + 1) % len(self.data)
self.count -= 1
return item
queue = CircularQueue(4)
for tag in ["A", "B", "C"]:
queue.enqueue(tag)
print(queue.dequeue())
print(queue.dequeue())
queue.enqueue("D")
queue.enqueue("E")
print(queue.data)
print(queue.dequeue())Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 2 to 5 set up the store: 4 slots, front at 0, count at 0.
- Lines 7 to 12 define enqueue. The full guard refuses overfilling. The rear is computed with wrap, then the item is stored and the count grows.
- Lines 14 to 20 define dequeue. The empty guard comes first. Then the front is read, stepped with wrap, and the count shrinks.
- Lines 22 to 24 add A, B and C at slots 0, 1 and 2.
- The next two prints serve A, then B. The front steps to 2, leaving C waiting.
- Adding D uses slot 3 and adding E wraps to slot 0. The printed list shows the raw slot order.
- The final dequeue serves C. Wrap reused slot 0 without moving any entry.
A
B
['E', 'B', 'C', 'D']
CCreate the queue with size 2 instead. Predict which call first raises the full error.
| After step | Slots 0 to 3 | Front | Count |
|---|---|---|---|
| A, B, C added | A, B, C, empty | 0 | 3 |
| Serve A, then B | A, B, C, empty | 2 | 1 |
| Add D, then E | E, B, C, D | 2 | 3 |
Read the table. The middle row still displays A and B in their slots. Those values are stale: count 1 means only slot 2, holding C, is live. Dequeue never clears a slot; it moves the front and shrinks the count. The last row shows E wrapped into slot 0. Raw slot order is not service order.
When front and rear markers coincide, the store may be empty or full. This class answers with count: zero means empty, size means full.
An alternative design leaves one slot unused and reads coincidence as empty. Either choice must be stated and used consistently.
Test an empty queue, a single entry, multiple arrivals, and arrivals interleaved with removals. Verify the sequence of removed entries as well as the final size.
Then test the circular store twice around the wrap: fill it, empty it partly, fill it again, and confirm old entries never reappear.
Record the slot contents after every step, not only the printed values. Stale slots look occupied but count as free.
The table above shows exactly that trap: A and B linger on screen after being served, yet the count proves they are gone.
A queue function written for this chapter uses pop() with no index for dequeue. It drops the newest tag instead of the oldest. What is the repair?
Goal. Make dequeue remove the oldest waiting entry.
Approach. Ask which end pop() without an index removes, and which end the front occupies.
Trace. The list end is the rear, so pop() takes the newest arrival. The front lives at index 0.
Result. Remove from the front with pop(0), keeping append for the rear.
Result: Change pop() to pop(0) inside dequeue. The repair moves removal to the front end.
4.4 INTRODUCTION TO DEQUE
A deque allows insertion and removal at both ends. That flexibility can model several behaviours. The program must still say which operations it permits for a particular task.
For ordinary waiting work, add at the rear and remove at the front. For an undo pile, use one end for both operations. For comparing the outer characters of a word, remove from both ends.
- Identify the behaviour required by the task.
- Choose the endpoint operations that preserve that behaviour.
- Explain any exception, such as inserting an urgent item ahead of older work.
Some tasks need efficient access at both ends rather than a fixed FIFO restriction.
A deque, pronounced deck, is a double-ended queue. Its operations can add or remove at either end.
A deque can implement a stack, a queue or another carefully stated policy. The available operations do not themselves decide which policy your program follows.
| Operation in collections.deque | End affected |
|---|---|
| append(x) | Add at right. |
| appendleft(x) | Add at left. |
| pop() | Remove at right. |
| popleft() | Remove at left. |
Read the table. Two operations grow the structure, one per end. Two operations shrink it, one per end. The table names ends, not policies. Your program chooses the policy by pairing them.
A deque supplies operations at both ends. The application supplies the policy for using them.
For a queue with front on the left, append and popleft maintain FIFO. For a stack with top on the right, append and pop maintain LIFO.
A restricted-input deque permits insertion at only one end; a restricted-output deque permits removal at only one end.
Picture a forms desk. Anyone may hand in a form at the rear, but only the clerk removes finished forms from the front.
That is restricted-output in daily dress: many may insert, yet removal belongs to one end. Restricted-input is the mirror: insertion at one end only, with removal from either end under a stated rule.
A deque is not the answer to every access question. Reading a middle entry by position is slow on a deque, because it must walk in from one end.
A list serves positional reads; a deque serves endpoint traffic. Choose the container from the access pattern the task repeats most.
Try to predict the printed result first. The trace below explains every line.
from collections import deque
pile = deque()
pile.append("plate 1")
pile.append("plate 2")
print(pile.pop())
print(list(pile))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 imports the deque container.
- Line 2 creates an empty deque for the pile.
- Lines 3 and 4 append 2 plates at the right end. Plate 2 sits on the top.
- Line 5 pops from the same right end and prints plate 2. One end did both jobs, so the behaviour is LIFO.
- Line 6 shows plate 1 still stored.
plate 2
['plate 1']Append "plate 3" after line 4. Predict both printed lines.
The same container behaves as a queue when opposite ends are paired. The next program feeds the same three tags through a stack discipline and a queue discipline side by side.
Watch which tag each structure releases first.
Before running the program, say the output in your own words.
from collections import deque
stack = []
queue = deque()
for tag in ["S1", "S2", "S3"]:
stack.append(tag)
queue.append(tag)
print(stack.pop())
print(queue.popleft())
print(stack)
print(list(queue))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Lines 1 to 3 prepare an empty list stack and an empty deque queue.
- Lines 4 to 6 store the same 3 tags in both. Each structure keeps its own order.
- Line 7 pops the list end and prints S3, the newest.
- Line 8 poplefts the deque front and prints S1, the oldest.
- Lines 9 and 10 show the remains: the stack kept the two oldest, while the queue kept the two newest.
S3
S1
['S1', 'S2']
['S2', 'S3']Add "S4" to the tag list. Predict all four printed lines.
The same deque also serves as an ordinary FIFO queue when opposite ends are paired. The next program stores three crates and serves them from the front. Compare its output order with the plate program above.
Write down what this program should print before you read the expected output.
from collections import deque
desk = deque()
desk.append("crate 1")
desk.append("crate 2")
desk.append("crate 3")
print(desk.popleft())
print(desk.popleft())
print(list(desk))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 imports the deque container.
- Line 2 creates an empty service desk.
- Lines 3 to 5 append three crates at the right rear. Crate 1 is the oldest.
- Line 6 serves the left front and prints crate 1.
- Line 7 serves the new front and prints crate 2.
- Line 8 shows crate 3 still waiting. Opposite ends give FIFO.
crate 1
crate 2
['crate 3']Serve once more after line 7. Predict both printed lines.
A deque removes from the left without shifting the rest. That is why long waiting lines prefer it to list pop(0). The FIFO meaning is identical; only the cost differs.
A program uses a deque with append and pop only, and calls the result a queue. Is that correct?
Goal. Judge whether one-ended deque use gives queue behaviour.
Approach. Ask which end each operation touches and which entry leaves first.
Trace. Both operations touch the right end, so the newest entry leaves first. That is LIFO, the stack rule from the previous chapter.
Result. The policy decides the name, not the container.
Result: No. Append with pop is a stack built from a deque, not a queue.
Same container skills, opposite pairing. One end twice gives LIFO. Opposite ends give FIFO. State the pairing before you claim the policy.
Read the diagram. The first two boxes list what each end can do. The third box pairs opposite ends for FIFO service. The last box pairs one end with itself for LIFO. The diagram is a choice menu, not a sequence.
A task list accepts an urgent task at the front and a routine task at the rear. Is it still a plain FIFO queue?
Goal. Decide whether two-ended insertion preserves first in, first out.
Approach. Ask whether a new arrival can overtake older waiting work.
Trace. The urgent insertion can move ahead of older work. That policy uses two-ended insertion.
Result. The order now depends on declared urgency, not arrival alone.
Result: No. It is a deque-based policy, and its priority rule should be explained.
A palindrome check is another useful application: compare and remove the two end values until no unmatched pair remains. Decide first whether spaces and letter case matter.
Section 4.5 builds it with endpoint removals on both sides.
4.5 IMPLEMENTATION OF DEQUE USING PYTHON
A palindrome reads the same in both directions. You can compare its outer characters first. When they match, those characters no longer need attention; the same question remains for the smaller middle.
Using a deque makes the two-ended removal explicit. If a pair differs, you already know the answer is false. If no unequal pair is found before the middle is reached, the comparisons have succeeded.
- Compare the leftmost and rightmost remaining characters.
- Stop immediately if they differ.
- Otherwise remove that pair and repeat on the remaining middle.
Use library operations when their contracts match the required behaviour.
Python supplies deque in the collections module. Its endpoint operations run efficiently even for long waiting lines. Import it, then pair its ends the way the task requires.
Predict the output before running this complete example.
from collections import deque
waiting = deque(["batch A", "batch B"])
waiting.append("batch C")
print(waiting.popleft())
waiting.appendleft("urgent")
print(list(waiting))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Append puts routine work on the right.
- Popleft serves the oldest entry on the left.
- Appendleft then places urgent work ahead of the remaining entries. This intentionally changes the service policy.
batch A
['urgent', 'batch B', 'batch C']Replace appendleft with append and compare the resulting order.
Line 1 imports deque. Line 2 stores two batches with batch A at the left front. Line 3 appends batch C at the right rear. Line 4 serves the front and prints batch A.
Line 5 is the deliberate exception: appendleft places urgent work ahead of older entries. Line 6 shows the result.
The same container now breaks FIFO on purpose. The printed list proves the policy changed, so document it.
The ticket counter returns in deque form. Routine tokens join the rear. Service takes the front. One urgent token jumps the line, openly and visibly.
Try to predict the printed result first. The trace below explains every line.
from collections import deque
counter = deque(["token 1", "token 2"])
counter.append("token 3")
print(counter.popleft())
counter.appendleft("urgent token")
print(list(counter))
print(counter.popleft())Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 stores 2 tokens with token 1 at the front.
- Line 2 is a routine arrival at the rear.
- Line 3 serves token 1, the oldest.
- Line 4 is the stated exception: an urgent token joins the front.
- Line 5 shows the line with urgent work first.
- Line 6 serves that urgent token next. Priority overtook arrival by design.
token 1
['urgent token', 'token 2', 'token 3']
urgent tokenReplace appendleft with append in line 4. Predict the last two printed lines.
| After step | Counter from front to rear |
|---|---|
| Start | token 1, token 2 |
| Routine arrival | token 1, token 2, token 3 |
| Serve one | token 2, token 3 |
| Urgent joins front | urgent token, token 2, token 3 |
| Serve one | token 2, token 3 |
Read the table. Each row freezes the counter after one step. Routine service removes from the left and preserves order. The urgent row is the only one that inserts at the left. The final row proves the exception was a single event: ordinary order resumes at once.
An empty deque needs the same guard as an empty list queue. Test before popleft or pop, and report the empty state in plain words. The library does not read your mind about what empty should mean.
The len function works on a deque and reports its current size in one step. The programs above rely on that: the loop condition, the final report and the emptiness test all read the same live count.
Before running the program, say the output in your own words.
from collections import deque
waiting = deque()
if waiting:
print(waiting.popleft())
else:
print("empty: nobody is waiting")
waiting.append("bus 1")
print(waiting.popleft())
print(len(waiting))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 creates an empty deque.
- Line 2 tests it. An empty deque counts as false.
- Line 5 runs instead and reports the empty state.
- Line 6 adds one bus entry.
- Line 7 serves it safely.
- Line 8 prints 0: the line is empty again.
empty: nobody is waiting
bus 1
0Remove line 6. Predict all three printed lines.
Serving a whole line needs no guard inside the loop when the loop condition is the test itself. While the deque is non-empty, a front entry must exist.
The program below prints every bus in order, then reports the empty state once.
Write down what this program should print before you read the expected output.
from collections import deque
line = deque(["bus 1", "bus 2"])
while line:
print(line.popleft())
print("line empty:", len(line) == 0)Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 stores two buses with bus 1 at the front.
- Line 2 repeats while entries wait. The test itself guarantees a safe removal.
- Lines 3 and 4 serve bus 1, then bus 2, each time printing the oldest.
- Line 5 runs after the loop. The length is 0, so the report prints True.
bus 1
bus 2
line empty: TrueStart with three buses instead of two. Predict all four printed lines.
Predict the output before running this complete example.
from collections import deque
def palindrome(text):
letters = deque(text)
while len(letters) > 1:
if letters.popleft() != letters.pop():
return False
return True
print(palindrome("level"))
print(palindrome("lever"))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Deque stores the characters in their original order.
- Each iteration removes an outer pair and compares it.
- A mismatch returns False immediately; matching pairs leave a smaller problem.
- If no unequal pair is found, the final return accepts the text.
True
FalseTry a word with mixed case and decide whether your own specification should ignore case.
The function stores the characters in order. Each loop compares the outer pair: popleft reads the left end and pop reads the right end.
A mismatch returns False at once. Matching pairs are discarded, leaving a smaller middle to test.
| Remaining letters | Outer pair | Decision |
|---|---|---|
| level | l and l | Match, discard the pair. |
| eve | e and e | Match, discard the pair. |
| v | Single middle letter. | Stop, answer true. |
Read the table. Each row is one loop pass on the word level. The first two rows discard matching outer pairs. The last row has no pair left to compare, so the word passes. The word lever would stop earlier at its first mismatch.
Read the diagram. The first box compares one outer pair. The next two boxes are the alternatives: mismatch ends the test, match shrinks it. The fourth box repeats the test on the middle. The last box accepts only when every pair agreed.
The loop compares outer pairs and discards them only after reading their values. An empty string and a one-character string pass because there is no unequal pair.
This version compares exactly the characters supplied; it does not remove spaces or normalise case.
The word lever fails at its first pair: l against r. One mismatch ends the test, so later letters are never compared. Early exit is what keeps the check fast on words that are not palindromes.
A bounded deque can discard an item from the opposite end when a new item exceeds its maximum length. That is useful for a rolling history but is not the same as rejecting overflow in a fixed-capacity queue.
Try to predict the printed result first. The trace below explains every line.
from collections import deque
recent = deque(maxlen=3)
for mark in [5, 7, 9, 6]:
recent.append(mark)
print(list(recent))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 fixes the memory at the last 3 marks. Older marks will be evicted automatically.
- Lines 2 and 3 feed four marks through that memory.
- The marks 5, 7 and 9 fill it first. Then 6 arrives and evicts the oldest, 5.
- Line 4 prints the surviving window.
[7, 9, 6]Change maxlen to 2. Predict the printed list.
Use a maxlen memory when only the latest window matters, such as recent readings on a display. Use refusal when every entry matters, such as jobs waiting for a printer.
The question is not which container is better, but which loss rule the task allows.
A rolling memory forgets by design; a waiting line must not forget by accident. Choose maxlen eviction only when losing old entries is acceptable. Otherwise refuse the overflow loudly, as section 4.3 shows.
Endpoint operations shrink a problem from the outside in. Each palindrome pass removes two decided characters. Each queue pass removes one served entry. The structure fits the direction of the work.
Summary
Use these points to test what you can explain without looking back.
- A queue is FIFO: enqueue at the rear and dequeue at the front.
- The front is where service happens; the rear is where arrivals join.
- Peek inspects without removal; dequeue removes and reports.
- Specify underflow and any capacity limit before coding.
- Guard every uncertain dequeue with an emptiness test.
- List pop(0) demonstrates FIFO but shifts later entries.
- A fixed linear store can report full while freed slots stand unused.
- A circular store wraps its markers with the remainder operation and reuses freed slots.
- The remainder maps any step past the last slot back to the start of the store.
- A stale slot display proves nothing; the front marker and the count decide which entries are live.
- When front and rear coincide, a count tells empty from full.
- A deque supports both ends and can implement several policies.
- FIFO pairs opposite ends; LIFO pairs one end with itself.
- A rolling maxlen memory evicts old entries by design and must not back a no-loss queue.
- Endpoint efficiency does not supply concurrency control or application-level fairness by itself.
- Trace every program line by line, and change one input to test understanding.
Exercise
Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.
4.1 Enqueue A, B and C, dequeue once, enqueue D, then dequeue twice. State the removals and the remaining queue.
4.2 Distinguish a stack from a queue using their operation ends.
4.3 Why should a queue interface document its empty case?
4.4 Predict the full output of this bus-line program, then explain each line.
Before running the program, say the output in your own words.
line = ["bus 1", "bus 2", "bus 3"]
print(line.pop(0))
line.append("bus 4")
print(line.pop(0))
print(line)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores three buses with bus 1 at the front.
- Line 2 serves bus 1 and prints it.
- Line 3 is a new arrival. Bus 4 joins the rear behind bus 3.
- Line 4 serves bus 2 and prints it.
- Line 5 shows bus 3 at the front with bus 4 behind it.
bus 1
bus 2
['bus 3', 'bus 4']Append "bus 5" after line 3 and predict all three printed lines.
4.5 This dequeue removes the wrong end. Name the faulty call and give the repair.
def dequeue(queue):
if not queue:
raise IndexError("empty queue")
return queue.pop()4.6 Does peek change the result of is_empty? Explain.
4.7 A fixed-capacity queue holds three entries and a fourth arrives. Name two honest policies and one dishonest one.
4.8 Write a bounded enqueue that refuses a fourth entry with IndexError("queue is full"). Fill it with bus 1, bus 2 and bus 3, then attempt bus 4 inside try, and print the outcome.
4.9 A circular store has size 4, front at 2 and three entries waiting. Which slot takes the next enqueue, and why?
4.10 Explain why a fixed linear store can report full while free slots exist, and how wrapping repairs it.
4.11 Which deque operations model a queue with the front on the left, and which model a stack with the top on the right?
4.12 Predict both printed lines of this palindrome test, then explain each loop pass.
Try to predict the printed result first. The trace below explains every line.
from collections import deque
def is_palindrome(text):
letters = deque(text)
while len(letters) > 1:
if letters.popleft() != letters.pop():
return False
return True
print(is_palindrome("refer"))
print(is_palindrome("queue"))Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- The call with refer compares r with r, then e with e. One middle letter remains, so it returns True.
- The call with queue compares q with e at once. They differ, so it returns False immediately.
True
FalseTest "civic" and predict its printed line.
4.13 Explain why an urgent-front task list is not plain FIFO.
4.14 Why is a bounded deque useful for recent activity but risky as an assumed no-loss queue?
4.15 A printer line needs FIFO but an Undo feature needs LIFO. Which structure serves each, and what happens if they are swapped?
4.16 Write a counter program that serves every waiting token in order and collects the served tokens in a list. Start from token 1, token 2 and token 3.
4.17 A circular queue serves A and B, but its slots still display A and B. Must the program clear those slots? Explain.
4.18 A serve-all loop tests the queue itself as its condition. Why is no separate empty guard needed inside it?
Answers
4.1 Removed A, then B, then C. D remains alone. The first dequeue serves A. D joins behind C. The next two dequeues serve B, then C.
4.2 A stack inserts and removes at one end, the top. A queue inserts at the rear and removes at the front.
4.3 Callers need to know whether dequeue raises, waits, or returns a documented sentinel. An undocumented crash or a silent invented value both mislead.
4.4 Bus 1, then bus 2, then the list with bus 3 and bus 4. Each pop(0) removes the current front, and the append joins the rear.
4.5 pop() without an index removes the rear, which is the newest arrival. The repair is pop(0), which removes the front, the oldest waiting entry.
4.6 No. Peek only observes the front. The entry count is unchanged, so is_empty answers as before.
4.7 Refuse the new entry with a clear error, or wait for space under a documented rule. Silently discarding an old waiting entry is dishonest because waiting work vanishes.
4.8 The first three enqueues succeed and the fourth is refused. The queue prints as [bus 1, bus 2, bus 3] with the overflow message.
Write down what this program should print before you read the expected output.
def enqueue(queue, item):
if len(queue) >= 3:
raise IndexError("queue is full")
queue.append(item)
queue = []
try:
for tag in ["bus 1", "bus 2", "bus 3", "bus 4"]:
enqueue(queue, tag)
except IndexError as error:
print("Overflow:", error)
print(queue)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Lines 1 to 4 define enqueue with a capacity rule of 3.
- The loop admits bus 1, bus 2 and bus 3 safely.
- The fourth call breaks the rule, so the raise ends the loop.
- The handler prints the message. The queue keeps its three entries.
Overflow: queue is full
['bus 1', 'bus 2', 'bus 3']Change the capacity to 2 and predict both printed lines.
4.9 Slot 1, because (2 + 3) divided by 4 leaves remainder 1. The rear wraps past the end of the row.
4.10 Served slots behind the front stay unreachable when markers only move right. Wrap-around lets both markers return to the start and reuse freed slots.
4.11 append with popleft gives the queue. append with pop gives the stack. The pairing decides the policy.
4.12 True, then False. The first word loses matching outer pairs until one middle letter remains. The second word fails on its first outer pair.
4.13 A new urgent task can precede older waiting tasks. Service then follows declared urgency, not arrival order alone.
4.14 It can evict old entries automatically, which loses waiting work if the application expected rejection or blocking.
4.15 The printer needs a queue and Undo needs a stack. Swapped, the printer would serve the newest job first and Undo would reverse the oldest action first.
4.16 The served list prints as [token 1, token 2, token 3]. The loop ends exactly when the counter is empty, so no guard message is needed inside it.
Before running the program, say the output in your own words.
from collections import deque
counter = deque(["token 1", "token 2", "token 3"])
served = []
while counter:
served.append(counter.popleft())
print(served)Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 1 stores three tokens with token 1 at the front.
- Line 2 prepares the empty served record.
- Lines 3 and 4 repeat while tokens wait. Each pass poplefts the current oldest.
- Line 5 prints the served record in arrival order.
['token 1', 'token 2', 'token 3']Start from two tokens instead and predict the printed list.
4.17 No. The count and the front marker decide which slots are live. Stale displays are ignored until wrapped writes overwrite them.
4.18 The loop body runs only while an entry waits, so each dequeue meets a non-empty queue. The condition is the guard.