Queue in Python

Queue in Python

Queue in Python

Introduction

A queue is a fundamental data structure in computer science that follows the FIFO (First In, First Out) principle. This means that elements are inserted at the rear and removed from the front, similar to a real-life queue (like waiting in line for a bus). Queues are widely used in various applications such as operating systems, task scheduling, and buffering processes.

In this tutorial, we will explore:

  • The basic concept of a queue
  • Built-in Python queue classes
  • Implementing a queue using Python

Complete Python Course with Advance topics:-Click here

What is a Queue?

A queue is a linear data structure used to store elements sequentially, following the FIFO principle. In a queue, the two primary operations are:

  1. Enqueue: Putting something in the queue.
  2. Dequeue: Taking an item out of the queue.

Example Scenario

Consider a computer science lab where 20 computers are connected to a single printer. When students send print requests, the printer processes the first request before moving on to the next, ensuring FIFO order.

Operations in a Queue

Python supports several queue operations:

  • Enqueue: Adds an item to the queue (Time Complexity: O(1)).
  • Dequeue: Removes an item from the queue (Time Complexity: O(1)).
  • Front: Returns the front item (Time Complexity: O(1)).
  • Rear: Returns the last item (Time Complexity: O(1)).

Implementing a Queue in Python

Using Lists (Not Recommended for Performance)

Python lists can be used as queues, but they are inefficient due to shifting operations when removing elements.

# Implementing a Queue using a List
queue = []
queue.append('Apple')
queue.append('Mango')
queue.append('Papaya')
print(queue)  # ['Apple', 'Mango', 'Papaya']

# Dequeue operation
print(queue.pop(0))  # Apple

The pop(0) operation takes O(n) time, making it inefficient for large-scale applications.

Using the Queue Class

A better approach is to implement a queue using a class.

Enqueue Operation

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

    def enqueue(self, val):
        self.queue.insert(0, val)  # Insert at the beginning

    def size(self):
        return len(self.queue)

q = Queue()
q.enqueue("Apple")
q.enqueue("Mango")
print("Queue Size:", q.size())  # Queue Size: 2

Dequeue Operation

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

    def enqueue(self, val):
        self.queue.insert(0, val)

    def dequeue(self):
        if len(self.queue) > 0:
            return self.queue.pop()
        return "Queue is Empty"

q = Queue()
q.enqueue("January")
q.enqueue("February")
print(q.dequeue())  # January

Using Python’s queue Module

Python provides a built-in queue module that offers thread-safe implementations.

from queue import Queue
q = Queue()
q.put("Apple")
q.put("Mango")
print(q.get())  # Apple

Available Methods

  • put(item): Inserts an item into the queue.
  • get(): Clears the queue of an item.
  • qsize(): Returns the queue size.
  • empty(): Verifies that there is nothing in the queue.
  • full(): verifies whether the queue is full.

Using collections.deque

The deque class from collections is an efficient way to implement a queue.

from collections import deque
q = deque()
q.append("Apple")
q.append("Mango")
print(q.popleft())  # Apple

Deque operations take O(1) time, making them more efficient than lists.

Using multiprocessing.Queue

This is useful for multi-processing applications.

from multiprocessing import Queue
q = Queue()
q.put("Apple")
q.put("Mango")
print(q.get())  # Apple

Implementing a Priority Queue

A Priority Queue retrieves elements based on priority rather than order.

import heapq
pq = []
heapq.heappush(pq, (1, "Low Priority"))
heapq.heappush(pq, (3, "High Priority"))
print(heapq.heappop(pq))  # (1, 'Low Priority')

Download New Real Time Projects :-Click here
Complete Advance AI topics:- CLICK HERE

Conclusion

Queues are an essential data structure with multiple implementations in Python. Your particular use case will determine which option is appropriate for you:

  • Use collections.deque for general-purpose queues.
  • Use queue.Queue for thread-safe applications.
  • Use multiprocessing.Queue for multi-processing.

Mastering queues will help you optimize programs that rely on order-based processing, such as scheduling, task management, and data buffering.


stack in python
Queue in Python
implement queue in python
queue in python w3schools
priority queue in python
circular queue in python
deque python
python queue example
types of queue in python
linked list in python
set in python
queue in python geeksforgeeks

Post Comment