📄 Need a professional CV? Try our Resume Builder! Get Started

Understanding the Queue Data Structure in Python

Welcome to this comprehensive tutorial! Today, we will dive into the concept of the Queue data structure, how it works, and its implementation in Python. Whether you're new to data structures or just need a refresher, this blog will guide you step-by-step with visual explanations and practical examples.

Date: Sun Jan 12, 2025

Introduction to Queue

"A queue is a linear data structure where elements are added and removed in a specific order: First In, First Out (FIFO)." — Data Structures 101

So, what exactly is a queue? A queue is a linear data structure that operates on the principle of First In, First Out (FIFO). This means that the first element added to the queue is the first one to be removed. Think of a line at a ticket counter — the person who arrives first is the first one to be served!

The primary operations of a queue are enqueue (adding an item) and dequeue (removing an item). Let's visualize these concepts.

Example of Queue Operations

Let's explore how queue operations work in practice. We'll perform a series of operations:

  • Enqueue 2, 3, 4, 5, 6, 7 (Adding elements to the queue)
  • Dequeue 2 (Removing the front element)
  • Enqueue 11 (Adding a new element)
  • Front (Checking the front element without removing it)

Queue Implementation in Python

Here's a robust implementation of a queue in Python with additional features and error handling:


class Queue:
    def __init__(self, max_size=None):
        """Initialize queue with optional maximum size."""
        self.container = []
        self.max_size = max_size

    def is_empty(self):
        """Check if queue is empty."""
        return len(self.container) == 0

    def is_full(self):
        """Check if queue has reached maximum size."""
        if self.max_size:
            return len(self.container) >= self.max_size
        return False

    def enqueue(self, data):
        """Add an element to the end of the queue."""
        if self.is_full():
            raise OverflowError("Queue overflow! Maximum size reached")
        self.container.append(data)
        return True

    def dequeue(self):
        """Remove and return the front element from the queue."""
        if self.is_empty():
            raise IndexError("Queue underflow! Queue is empty")
        return self.container.pop(0)

    def front(self):
        """Return the front element without removing it."""
        if self.is_empty():
            raise IndexError("Queue is empty!")
        return self.container[0]

    def size(self):
        """Return the current size of the queue."""
        return len(self.container)

    def __repr__(self):
        return str(self.container)

# Example usage
q = Queue()
q.enqueue(1)
q.enqueue(2)
print(q.dequeue())  # Output: 1