How to implement a queue in Python

Key takeaways:

  • A queue is a linear data structure that processes elements in the order they are added, following the First-In/First-Out (FIFO) method. The primary operations are enqueue (adding an element), dequeue (removing an element), front (accessing the first element), and rear (accessing the last element).

  • Queues in Python can be implemented using lists (with append() and pop(0)), the Queue module (using methods like put(), get(), and empty()), or the collections.deque module (using append() and popleft() for efficient operations).

  • While lists offer simplicity, deque provides efficient operations, and the Queue module adds thread safety, making it suitable for concurrent programming scenarios.

Queue is a linear data structure that stores items in a First-In/First Out (FIFO) manner. In the queue, the data element that is inserted first will be removed first.

Queue operations

Operations that can be performed on the queue are:

  1. Enqueue: It adds an item to the queue. If the queue is full, then it is said to be an overflow condition.

  2. Dequeue: It removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition.

  3. Front: It gives the front item from the queue.

  4. Rear: It gives the last item from the queue.

Note: The time complexity for all of the above operations is O(1)O(1).

1 of 5

In a queue, “peek” refers to the operation of viewing the element at the front of the queue without removing it. This allows you to check the first element without modifying the queue.

When working with a queue in Python, you typically don’t have a direct peek() method (as you might in other data structures). However, you can access the front element by using indexing.

If you want to peek at the front of the queue, you can use the index 0.

The -1 index refers to accessing the last element in the queue. In Python, negative indexes start from the end of the list. So:

  • queue[-1] will return the last element in the queue (the rightmost side in a deque).

So, to summarize:

  • queue[0]: Peeks at the front of the queue (first element).

  • queue[-1]: Peeks at the back of the queue (last element).

Methods to implement a queue

Queue in Python can be implemented in the following ways:

  1. Using Python lists

  2. Using Queue module

  3. Using the collections.deque module

1. Using python lists

In Python lists, we can use the append() method to add elements to the end of the list, effectively simulating the enqueue operation and the pop() method to remove elements from the beginning with an index of 0, effectively simulating the dequeue operation easily.

# implementing Queue using List :
q=[]
q.append(10)
q.append(100)
q.append(1000)
q.append(10000)
print("Initial Queue is:",q)
print(q.pop(0))
print(q.pop(0))
print(q.pop(0))
print("After Removing elements:",q)
def is_empty():
return len(q) == 0
def size():
return len(q)
print("Check queue is empty or not", is_empty())
print("Size of the queue:", size())

2. Using the Queue module

The Queue module in Python provides a convenient and thread-safe way to implement a FIFO (First-In-First-Out) queue. We have used the following methods to implement the queue:

  • put(): It inserts the specified element into the queue.

  • get(): It removes and returns the element at the front of the queue.

  • empty(): It returns True if the queue is empty; otherwise, it returns False.

  • qsize(): It returns the size of the queue.

# implment queue using queue module
from queue import Queue
q=Queue(maxsize=4)
print("Initial Size Before Insertion:",q.qsize())
q.put('A')
q.put('AA')
q.put('AAA')
q.put('AAAA')
print("After Insertion:",q.qsize())
print("Queue is Full or Not:",q.full())
print("Size of Queue:",q.qsize())
print("Removing Elements:")
print(q.get())
print(q.get())
print(q.get())
print("Empty or Not??",q.empty())
print(q.get())
print("Empty or Not??",q.empty())
print("Size of Queue:",q.qsize())

3. Using collections.deque module

The collections.deque module in Python provides a double-ended queue (deque) that allows adding and removing elements efficiently from both ends. The following methods we have used to implement queue:

  • append(): It inserts the specified element into the queue.

  • popleft(): It removes and returns the element at the front of the queue.

To get elements from the other side of the deque (the right end), you can use the pop() method, which removes and returns the element at the end of the queue.

from collections import deque
q=deque()
q.append(10)
q.append(100)
q.append(1000)
q.append(10000)
print("Initial Queue is:",q)
print(q.popleft())
print(q.popleft())
print("After Removing elements:",q)

Learn the basics with our engaging course!

Start your coding journey with our “Learn Python” course, the perfect course for absolute beginners! Whether you’re exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun along the way. Join now and start your Python journey today—no prior experience is required!

Conclusion

Queues are fundamental data structures that adhere to the First-In/First-Out (FIFO) principle, making them essential for various real-world applications like scheduling and buffering. Python offers multiple ways to implement queues, each suited to specific needs: lists for simplicity, the Queue module for thread-safe operations in concurrent programming, and the collections.deque module for efficient enqueue and dequeue operations. Understanding these implementations allows developers to choose the most suitable approach for their projects, ensuring efficiency and clarity in handling sequential data.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How does Python implement queue?

Python implements queues using lists, collections.deque for efficient operations, and the queue module for thread-safe FIFO queues.


Is the queue LIFO or FIFO?

A queue is FIFO (First-In, First-Out), meaning the first element added is the first one removed.


What is the difference between queue and deque?

A queue follows the FIFO principle for adding and removing elements, while a deque (double-ended queue) allows adding and removing elements efficiently from both ends.


How would you implement a stack or queue in Python?

1. Implementing a stack in Python:

A stack is a Last-In-First-Out (LIFO) data structure. In Python, it can be implemented using a list or the collections.deque class. Here is a simple implementation using a list:

# Stack implementation using a list

class Stack:
    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.append(item)  # Adds an item to the top of the stack

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()  # Removes the top item from the stack
        else:
            return "Stack is empty"

    def peek(self):
        if not self.is_empty():
            return self.stack[-1]  # Returns the top item without removing it
        else:
            return "Stack is empty"

    def is_empty(self):
        return len(self.stack) == 0  # Checks if the stack is empty

    def size(self):
        return len(self.stack)  # Returns the number of items in the stack

# Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())  # Output: 3
print(stack.peek())  # Output: 2

2. Implementing a queue in Python:

A queue is a First-In-First-Out (FIFO) data structure. It can also be implemented using a list or collections.deque. Here’s a simple implementation using a list:

# Queue implementation using a list

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

    def enqueue(self, item):
        self.queue.append(item)  # Adds an item to the end of the queue

    def dequeue(self):
        if not self.is_empty():
            return self.queue.pop(0)  # Removes and returns the first item from the queue
        else:
            return "Queue is empty"

    def peek(self):
        if not self.is_empty():
            return self.queue[0]  # Returns the first item without removing it
        else:
            return "Queue is empty"

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

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

# Example usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue())  # Output: 1
print(queue.peek())  # Output: 2

Alternative: Using collections.deque

deque is more efficient for both stack and queue operations (since list has O(n)O(n) time complexity for popping from the front, while deque provides O(1)O(1):

from collections import deque

# Stack using deque
stack = deque()
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop())  # Output: 3

# Queue using deque
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)
print(queue.popleft())  # Output: 1

Both methods provide efficient ways to implement stacks and queues in Python.


What is front and rear in a queue in Python?

In a queue, the front refers to the position of the first element that was added to the queue, while the rear refers to the position of the last element added to the queue.

  • Front: This is where elements are removed from the queue (FIFO - First In, First Out).
  • Rear: This is where new elements are added to the queue.

What is the difference between a queue and a lock in Python?

A queue in Python is a data structure for storing and retrieving elements in a specific order, while a lock is a synchronization primitive used to manage access to shared resources in concurrent programming.


Free Resources