8) Abstract Data Structures Lesson

How to Build a Python Queue

5 min to complete · By Martin Breuss

In the code example below, you see a possible way to implement a Queue class in Python. Note that you're using the same Node class that you implemented earlier when building your LinkedList to store the items in the queue:

class Node:
    def __init__(self, value=None):
        self.value = value
        self.next = None


class Queue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.length = 0
    
    def is_empty(self):
        return self.head is None

    def peek(self):
        if self.is_empty():
            return None
        else:
            return self.head.value
    
    def enqueue(self, value):
        new_node = Node(value)
        if self.is_empty():
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            self.tail = new_node
        self.length += 1
    
    def dequeue(self):
        if self.is_empty():
            return None
        else:
            dequeued_node = self.head
            self.head = self.head.next
            self.length -= 1
            if self.is_empty():
                self.tail = None
            return dequeued_node.value

5 Implemented Methods

This implementation of a Queue class has five methods:

  1. .__init__(): Initializes an empty queue with None values for the head and tail attributes.
  2. .is_empty(): Returns True if the queue is empty, False otherwise.
  3. .peek(): Checks if the queue is empty and returns None if it is. It returns the value of the first node if it's not empty.
  4. .enqueue(): Adds a new node with the given value to the end of the queue.
  5. .dequeue(): Removes and returns the value of the first node in the queue.

How to Use the Python Queue

To use your Queue class, you can create a new queue object and add some items to it using the .enqueue() method. Then, you can call the .dequeue() method on the queue object to remove and return the first item in the queue.

Here's an example of how you might use this Queue class to plan out your morning if you're not really a morning person and need reminders along the way:

# Create a new `Queue` object
morning_tasks = Queue()

# Add items to the queue during the previous night
morning_tasks.enqueue("get dressed")
morning_tasks.enqueue("eat breakfast")
morning_tasks.enqueue("go to work")

# Check what'll be your first task during a midnight wake-up without doing it
morning_tasks.peek()  # get dressed

# Fetch an element from the queue in the morning right after waking up
task = morning_tasks.dequeue()  # get dressed

print(f"Todo: {task}")  # Todo: get dressed

In this example, you call .dequeue() on the morning_tasks queue object once. That removes and returns the first item in the queue ("get dressed"). Once you've managed to get dressed, you can pop the next item from your queue to make sure you start the day like a champion!

Better Documentation

For a better representation of your Queue, when you print the whole thing, you could again implement a .__repr__() method for the class.

Colorful illustration of a light bulb

Addition Resources

In the next lesson, you'll further expand your Queue with a decorator to get an idea of how you can continue to build on top of these data structures, as well as train the concept of decorators and apply them to a custom class you're working on.

Summary: How to Build a Python Queue

  • This lesson provides sample code for creating a Python Queue
  • This Queue has five methods
    • .__init__()
    • .is_empty()
    • .peek()
    • .enqueue()
    • .dequeue()