Python: Queue Implementation with Lists

1. Introduction

A queue is a linear data structure that follows the First In First Out (FIFO) principle. Elements are added (enqueued) to the back and removed (dequeued) from the front. In this post, we will learn how to implement a queue using Python's built-in list.

2. Program Overview

1. Define a class called Queue.

2. Initialize an empty list in the constructor to represent the queue.

3. Define methods: enqueue, dequeue, is_empty, size, and peek.

4. Demonstrate the queue operations with some sample values.

3. Code Program

class Queue:
    def __init__(self):
        # Initialize an empty list to store elements of the queue
        self.items = []

    def enqueue(self, item):
        # Add the item to the end of the list (rear of the queue)
        self.items.append(item)

    def dequeue(self):
        # Remove the item from the front of the list (front of the queue) and return it
        if not self.is_empty():
            return self.items.pop(0)
        return None

    def is_empty(self):
        # Check if the queue is empty
        return len(self.items) == 0

    def size(self):
        # Return the number of items in the queue
        return len(self.items)

    def peek(self):
        # View the front item without removing it
        if not self.is_empty():
            return self.items[0]
        return None

# Demonstration:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print("Front of the queue:", queue.peek())
print("Size of the queue:", queue.size())
print("Dequeued:", queue.dequeue())
print("Size after dequeue:", queue.size())

Output:

Front of the queue: 1
Size of the queue: 3
Dequeued: 1
Size after dequeue: 2

4. Step By Step Explanation

1. A class named Queue is defined.

2. Inside the __init__ method, an empty list items is initialized. This list will act as our queue.

3. The enqueue method appends an item to the end of the list, thus adding it to the rear of the queue.

4. The dequeue method removes and returns the item at the start of the list, representing the front of the queue.

5. is_empty checks if the queue is empty by verifying the length of the items list.

6. size returns the count of items in the queue.

7. peek provides a view of the front item without removing it.

8. In the demonstration part, we initialize the queue, enqueue three items, peek at the front, and then dequeue an item, displaying the results at each step.

Comments