PYTHON

Implement a Basic Queue (FIFO) with Python Lists

Learn to build a First-In, First-Out (FIFO) queue data structure in Python using lists, demonstrating essential enqueue and dequeue operations for ordered data processing.

class Queue:
    def __init__(self):
        self._items = []

    def enqueue(self, item):
        """Adds an item to the rear of the queue."""
        self._items.append(item)

    def dequeue(self):
        """Removes and returns the item from the front of the queue.
        Raises an IndexError if the queue is empty.
        Note: Using list.pop(0) can be inefficient for very large queues
        as it requires shifting all subsequent elements."""
        if not self.is_empty():
            return self._items.pop(0)
        raise IndexError("dequeue from empty queue")

    def front(self):
        """Returns the item at the front of the queue without removing it.
        Raises an IndexError if the queue is empty."""
        if not self.is_empty():
            return self._items[0]
        raise IndexError("front from empty queue")

    def is_empty(self):
        """Checks if the queue is empty."""
        return len(self._items) == 0

    def size(self):
        """Returns the number of items in the queue."""
        return len(self._items)

    def __str__(self):
        return str(self._items)

# Example Usage:
my_queue = Queue()
print(f"Is queue empty? {my_queue.is_empty()}") # True

my_queue.enqueue("Task 1")
my_queue.enqueue("Task 2")
my_queue.enqueue("Task 3")
print(f"Queue after enqueues: {my_queue}") # ['Task 1', 'Task 2', 'Task 3']
print(f"Queue size: {my_queue.size()}") # 3

print(f"Front element: {my_queue.front()}") # Task 1
print(f"Dequeued element: {my_queue.dequeue()}") # Task 1
print(f"Queue after dequeue: {my_queue}") # ['Task 2', 'Task 3']

print(f"Dequeued element: {my_queue.dequeue()}") # Task 2
print(f"Queue after dequeue: {my_queue}") # ['Task 3']

print(f"Is queue empty? {my_queue.is_empty()}") # False
How it works: This Python snippet illustrates a basic implementation of a Queue, a First-In, First-Out (FIFO) data structure, using a standard Python list. Items are added to the rear using `enqueue()` (list `append()`) and removed from the front using `dequeue()` (list `pop(0)`). While functional, be aware that `pop(0)` can be inefficient for large queues as it requires shifting all subsequent elements. For highly optimized queues, `collections.deque` (not covered here due to specific constraints) is generally preferred.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs