How to Implement a Queue Class in Python Using deque
Build a FIFO queue class in Python backed by the collections.deque container with enqueue, dequeue, peek, and size methods.
Python code
38 linesfrom collections import deque
class Queue:
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if self.is_empty():
raise IndexError("dequeue from empty queue")
return self._items.popleft()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty queue")
return self._items[0]
def is_empty(self):
return len(self._items) == 0
def size(self):
return len(self._items)
def __repr__(self):
return f"Queue({list(self._items)})"
if __name__ == "__main__":
q = Queue()
for item in ["a", "b", "c"]:
q.enqueue(item)
print(f"Queue: {q}")
print(f"Size: {q.size()}")
print(f"Dequeue: {q.dequeue()}")
print(f"Peek: {q.peek()}")
print(f"Is empty: {q.is_empty()}")
print(f"Queue after operations: {q}")
Output
Queue: ['a', 'b', 'c']
Size: 3
Dequeue: a
Peek: b
Is empty: False
Queue after operations: ['b', 'c']
How it works
The collections.deque (double-ended queue) provides O(1) append and popleft operations, making it an ideal internal container for a FIFO queue. The __init__ method initializes the deque to store items, and each public method delegates to efficient deque operations. The dequeue and peek methods raise an IndexError for empty queues, which is consistent with Python's built-in container behavior. The __repr__ method gives a readable string representation by converting the deque to a list. This design keeps the implementation concise while maintaining thread-safe atomic operations for single-threaded use.
Common mistakes
- Using a regular list with pop(0) instead of deque, which makes dequeue O(n)
- Forgetting to check for empty queue before calling popleft or accessing index 0
- Not raising a clear error message when operating on an empty queue
- Using appendleft/pop on deque in the wrong order, turning FIFO into LIFO (stack behavior)
Variations
- Use `queue.Queue` from the stdlib for a thread-safe queue with blocking operations
- Implement with a fixed-size array and circular index counters for bounded queues
Real-world use cases
- Processing jobs in order at a web service where requests must be handled first-in-first-out.
- Managing a task queue in an automation worker that runs scheduled items sequentially.
- Buffering messages in a pub/sub consumer when events need to be processed in arrival sequence.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.