Back to Data Structures & Algorithms
2026-02-065 min read

Simple Queue (Data Structures & Algorithms)

Learn Simple Queue (Data Structures & Algorithms) step by step with clear examples and exercises.

Title: Simple Queue (Data Structures & Algorithms) - Python Implementation

Why This Matters

In programming, understanding data structures like queues is crucial as they are fundamental building blocks in various real-world applications such as operating system task scheduling, network packet processing, and browser tab management. This lesson will focus on implementing a simple queue using Python, covering its core concepts, common mistakes, practice questions, and frequently asked questions.

A queue follows the First In, First Out (FIFO) principle, where items are added to the rear of the queue and removed from the front. This order is essential for efficient resource management in many applications.

Prerequisites

To follow this lesson, you should have a good understanding of the following topics:

  • Basic Python syntax (variables, functions, loops, and conditional statements)
  • Data structures like lists in Python
  • Concepts of stacks and arrays
  • Familiarity with the enumerate() function

Core Concept

A simple queue can be implemented using a list in Python. The front of the queue represents the first element added, while the rear represents the last element added. Here's an example implementation:

class SimpleQueue:
def __init__(self):
self.queue = []

def enqueue(self, item):
"""Add an item to the queue."""
self.queue.append(item)

def dequeue(self):
"""Remove and return the front item from the queue."""
if not self.queue:
return None
return self.queue.pop(0)

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

def is_empty(self):
"""Check if the queue is empty."""
return not bool(self.queue)

def peek(self):
"""Return the front item without removing it."""
if not self.queue:
return None
return self.queue[0]

def __iter__(self):
"""Iterate through the queue items."""
for item in self.queue:
yield item

Worked Example

Let's create a simple queue and perform some operations using enqueue, dequeue, peek, size, is_empty, and iterating over the queue:

queue = SimpleQueue()
queue.enqueue("A")
queue.enqueue("B")
queue.enqueue("C")
print("Current queue:", list(queue)) # Output: ["A", "B", "C"]
print("Dequeued item:", queue.dequeue()) # Output: A
print("Current queue:", list(queue)) # Output: ["B", "C"]
print("Peek at the front of the queue:", queue.peek()) # Output: B
print("Queue size:", queue.size()) # Output: 2
print("Is the queue empty?", queue.is_empty()) # Output: False

Common Mistakes

  1. Ignoring the is_empty() method: It's essential to check if the queue is empty before attempting to dequeue an item, or you might encounter a IndexError.
queue = SimpleQueue()
print(queue.dequeue()) # Output: IndexError: empty queue
  1. Manipulating the queue directly: Avoid modifying the queue directly instead of using enqueue and dequeue methods, as it may lead to incorrect results or errors.
queue = SimpleQueue()
queue.queue.append("A")
print(queue.dequeue()) # Output: A
queue.queue.pop(0)
print(queue.dequeue()) # Output: None
  1. Not handling empty queue exceptions: It's good practice to handle exceptions when trying to dequeue an item from an empty queue.
class SimpleQueueException(Exception):
pass

class SimpleQueue:
def __init__(self):
self.queue = []

... other methods ...

def dequeue(self):

if not self.queue:

raise SimpleQueueException("Cannot dequeue from an empty queue.")

return self.queue.pop(0)


4. **Not considering the case when trying to enqueue more items than the queue's capacity**: If the queue has a fixed capacity, it is essential to handle this situation appropriately.

5. **Using the wrong method for a specific operation**: Be aware of which methods are used for each operation (enqueue, dequeue, peek, size, etc.) and use them accordingly.

Practice Questions

  1. Implement a method to check if an item is present in the queue without removing it (peek).
  2. Write a function that merges two queues into one using your SimpleQueue implementation.
  3. Implement a priority queue where items with lower values are dequeued first.
  4. Modify the SimpleQueue class to handle exceptions when trying to enqueue or dequeue an item from an empty queue.
  5. Create a method that returns the maximum value in a priority queue without removing it (peek_max).
  6. Implement a circular queue with a given capacity using your SimpleQueue implementation.
  7. Write a function that checks if two queues are identical in terms of their elements and order.
  8. Extend the SimpleQueue class to handle a priority queue, where items can be enqueued with their priorities (e.g., tuples containing an item and its priority).
  9. Implement a method that removes and returns the item with the highest priority from the priority queue without removing other items with lower priorities.
  10. Modify the SimpleQueue class to support both FIFO and LIFO (Last In, First Out) operations using two separate methods: dequeue_fifo() for FIFO and dequeue_lifo() for LIFO.

FAQ

What is a simple queue in Python?

A simple queue in Python is a data structure that follows the First In, First Out (FIFO) principle. It can be implemented using a list, where items are added to the rear and removed from the front.

How do I check if an item is present in a Python queue without removing it?

You can use the peek() method provided by the SimpleQueue class to check the front item of the queue without removing it. If the queue is empty, it will return None.

What happens when I try to dequeue from an empty Python queue?

If you attempt to dequeue from an empty Python queue, it will raise a SimpleQueueException (if the exception handling is implemented). By default, it will result in a IndexError.

How can I handle exceptions when trying to enqueue or dequeue items from a Python queue?

You can create a custom exception class called SimpleQueueException, and then raise this exception when attempting to enqueue or dequeue from an empty queue. The SimpleQueue class should be modified to catch these exceptions and provide appropriate error messages.

How do I implement a priority queue in Python using the SimpleQueue class?

To implement a priority queue, you can modify the SimpleQueue class to allow items with priorities (e.g., tuples containing an item and its priority). Then, you can sort the queue based on the priorities before adding or removing items. This will ensure that lower-priority items are dequeued first.

Simple Queue (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn