A queue follows first in, first out. Items join at the rear and leave from the front; collections.deque provides efficient operations at both ends. Trace head and tail positions after each enqueue or dequeue.
Watch out: Removing from the front of a normal Python list repeatedly can be less efficient than using a deque.
Study this example, identify inputs and outputs, then trace the key variables. Run and adapt it in Python 3.
from collections import deque
class Queue:
def __init__(self): self.items = deque()
def enqueue(self, value): self.items.append(value)
def dequeue(self):
if not self.items: raise IndexError("queue underflow")
return self.items.popleft()
def is_empty(self): return not self.items
q = Queue(); q.enqueue('A'); q.enqueue('B')
2 · Independent programming challenge
Implement a queue using collections.deque with enqueue and dequeue operations. Download the starter, design your solution, and add tests before revealing the answer.
Stretch task: investigate time/space complexity or data validation, then write an evaluation of your approach.
Show reference solution after attempting the task
from collections import deque
class Queue:
def __init__(self): self.items = deque()
def enqueue(self, value): self.items.append(value)
def dequeue(self):
if not self.items: raise IndexError("queue underflow")
return self.items.popleft()
def is_empty(self): return not self.items
q = Queue(); q.enqueue('A'); q.enqueue('B')
assert q.dequeue() == 'A' and q.dequeue() == 'B' and q.is_empty()
print('Queue tests passed')
3 · Debug and explain
Change one boundary condition in the starter or reference program. Predict which test fails, then repair it and document why.
Concept check: Why use deque rather than list.pop(0) for a large queue?
Reveal explanation
deque.popleft() is efficient; removing the first list element shifts the remaining elements.
4 · Assess your learning
Describe the algorithm or design in your own words; include a normal test, a boundary test and an invalid input. Compare your answers with the reference solution and record one improvement.
Trace front and rear positions while enqueueing and dequeueing. Explain how FIFO differs from a stack and why a circular queue can reuse space in a fixed-size array.
Quick check: Which item is removed first after enqueueing A, B and C?
Check: A, because the first item added is the first removed.