Queue in Python




A Queue in Python is a linear data structure that follows the FIFO (First In, First Out) principle — meaning the first element added is the first one removed.

Queues are widely used in task scheduling, data buffering, and asynchronous programming (like producer-consumer models).

 Front → [A, B, C, D] → Rear Enqueue(E) → [A, B, C, D, E] 
Dequeue() → removes A → [B, C, D, E] 

What is a Queue?

A Queue allows elements to be inserted at the rear (enqueue) and removed from the front (dequeue). It is ideal when you want to process elements in the order they arrive.

Basic Queue Operations:

Operation	Description

enqueue()	Add element to the queue
dequeue()	Remove element from front
peek()	        Return front element without removing
is_empty()	Check if queue is empty
size()	        Return number of elements

Method 1: Implementing Queue Using List

Python lists can be used to implement queues, though pop(0) is inefficient for large data because it shifts all elements left.


# Queue using List
queue = []

# Enqueue (add elements)
queue.append('A')
queue.append('B')
queue.append('C')
print("Queue after enqueues:", queue)

# Dequeue (remove from front)
item = queue.pop(0)
print("Dequeued:", item)
print("Queue after dequeue:", queue)

# Peek (view front element)
print("Front element:", queue[0])

Output:

 Queue after enqueues: ['A', 'B', 'C'] 
Dequeued: A Queue after dequeue: ['B', 'C'] 
Front element: B 

✅ Easy to implement for small datasets.
❌ Inefficient for large queues due to O(n) dequeuing.

Method 2: Queue Using collections.deque

deque (Double-Ended Queue) from the collections module provides an efficient implementation of queues. It supports O(1) operations for both ends.

from collections import deque

# Create a queue
queue = deque()

# Enqueue elements
queue.append('A')
queue.append('B')
queue.append('C')
print("Queue after enqueues:", queue)

# Dequeue element
print("Dequeued:", queue.popleft())
print("Queue after dequeue:", queue)

# Peek front element
print("Front element:", queue[0])

Output:

 Queue after enqueues: deque(['A', 'B', 'C']) 
Dequeued: A Queue after dequeue: deque(['B', 'C']) 
Front element: B 

✅ deque is the recommended queue implementation in Python.
✅ Provides thread-safe, memory-efficient, and fast operations.

Method 3: Queue Using queue.Queue (Thread-Safe)

The queue.Queue module provides a thread-safe FIFO queue, widely used in multi-threading applications.

from queue import Queue

# Create a FIFO queue
q = Queue(maxsize=3)

# Enqueue items
q.put('A')
q.put('B')
q.put('C')

print("Full:", q.full())
print("Size:", q.qsize())

# Dequeue items
print("Dequeued:", q.get())
print("Queue Empty?", q.empty())

Output:

 Full: True Size: 3 Dequeued: A Queue Empty? False 

✅ Ideal for multithreaded producer-consumer programs.
✅ Provides synchronization primitives.
❌ Slightly slower due to locking overhead.

Method 4: Queue Using multiprocessing.Queue

For multi-process applications, you can use multiprocessing.Queue, which allows communication between processes.

from multiprocessing import Process, Queue

def worker(q):
  q.put("Message from child process")

if name == "main":
q = Queue()
p = Process(target=worker, args=(q,))
p.start()
print(q.get()) # Receive message
p.join()

Output:

Message from child process

✅ Used for inter-process communication (IPC).
✅ Works across CPU cores.

Method 5: Queue Using OOP (Custom Implementation)

Let’s implement a Queue class manually to understand internal logic.

class Queue:
  def init(self):
     self.items = []

def is_empty(self):
    return len(self.items) == 0

def enqueue(self, item):
    self.items.append(item)
    print(f"Enqueued: {item}")

def dequeue(self):
    if not self.is_empty():
        removed = self.items.pop(0)
        print(f"Dequeued: {removed}")
        return removed
    print("Queue is empty!")

def peek(self):
    if not self.is_empty():
        return self.items[0]
    return None

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

# Example usage
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print("Front:", q.peek())
q.dequeue()
print("Size:", q.size())

Output:

 Enqueued: 10 Enqueued: 20 Enqueued: 30 Front: 10 Dequeued: 10 Size: 2 

✅ Easy to understand for beginners.
❌ Not efficient for heavy operations (uses list pop(0)).

Method 6: Priority Queue in Python

If you need elements processed by priority instead of order, use queue.PriorityQueue.

from queue import PriorityQueue

pq = PriorityQueue()

# Lower number = higher priority
pq.put((1, "Low"))
pq.put((0, "High"))
pq.put((2, "Medium"))

while not pq.empty():
   print(pq.get())

Output:

 (0, 'High') (1, 'Low') (2, 'Medium') 

✅ Great for scheduling, task queues, or Dijkstra’s algorithm.
✅ Automatically sorts items by priority.

💡 Real-World Use Case: Task Scheduling Simulation

from collections import deque
import time

tasks = deque(["Task1", "Task2", "Task3", "Task4"])

while tasks:
 task = tasks.popleft()
 print(f"Processing {task}...")
 time.sleep(1) # Simulate task execution

Output:

 Processing Task1... Processing Task2... Processing Task3... Processing Task4... 

Performance Comparison

Implementation	Enqueue	     Dequeue	Thread-safe	Recommended
List	            O(1)	O(n)	❌	         Basic use
deque	            O(1)	O(1)	❌	         Best general choice
queue.Queue	    O(1)	O(1)	✅	         Multi-threading
multiprocessing.Queue O(1)	O(1)	✅	         Multi-processing

Queue vs Stack in Python — Key Differences & Examples

A Stack is LIFO (Last In, First Out) — the last pushed item is the first popped.
A Queue is FIFO (First In, First Out) — the first enqueued item is the first dequeued.

This section shows when to use each, performance trade-offs, and short examples.

When to use?

Use a Stack when you need to backtrack (undo/redo), evaluate expressions (parsing), or manage function calls (recursion).

Use a Queue when you need ordered processing (task scheduling), producer-consumer patterns, or buffering.

FAQs — Queue in Python

What is a Queue in Python?

A Queue in Python is a linear data structure that follows the FIFO (First In, First Out) principle — the first element added is the first to be removed. Queues are useful in scheduling, buffering, and producer-consumer problems.

How to implement a Queue in Python using a list?

You can simulate a queue using list operations, but it’s inefficient for large data because pop(0) is O(n):

queue = []
queue.append('A')
queue.append('B')
print(queue.pop(0))  # Output: A

Use collections.deque for better performance.

How to create a Queue in Python using collections.deque?

deque from collections provides an efficient queue implementation:

from collections import deque
queue = deque()
queue.append('A')
queue.append('B')
print(queue.popleft())  # Output: A

append() adds to the rear, and popleft() removes from the front.

How to implement a Queue in Python using queue.Queue?

queue.Queue provides a thread-safe FIFO queue, ideal for multithreading:

from queue import Queue
q = Queue()
q.put(10)
q.put(20)
print(q.get())  # Output: 10

It supports blocking and timeout operations for concurrency control.

What are different types of Queues in Python?
  • FIFO Queue – First In First Out (queue.Queue)
  • LIFO Queue – Last In First Out (queue.LifoQueue)
  • Priority Queue – Items retrieved in sorted order (queue.PriorityQueue)
  • Deque Queue – Supports both ends (collections.deque)
How to check if a Queue in Python is empty?

Use the empty() method for queue.Queue or check directly for deque:

if not queue:
    print("Queue is empty")

What is the time complexity of Queue operations in Python?

For deque or queue.Queue:

  • enqueue (append/put): O(1)
  • dequeue (popleft/get): O(1)

Lists, however, have O(n) complexity for dequeue.

How to implement a custom Queue class in Python?
class Queue:
    def __init__(self):
        self.queue = []
    def enqueue(self, item):
        self.queue.append(item)
    def dequeue(self):
        if not self.is_empty():
            return self.queue.pop(0)
    def is_empty(self):
        return len(self.queue) == 0

How to use Queue in Python for multithreading?

queue.Queue is thread-safe, meaning multiple threads can safely enqueue and dequeue:

from queue import Queue
from threading import Thread

q = Queue()

def worker():
    while not q.empty():
        print(q.get())
        q.task_done()

for i in range(5):
    q.put(i)

t = Thread(target=worker)
t.start()
q.join()

When should you use a Queue in Python?

Use a Queue in Python when you need to manage tasks sequentially — such as scheduling, buffering, producer-consumer problems, or managing thread-safe data pipelines.


Related Post

Python SetPython Set

Python sets are a fundamental data structure used for storing unordered collections of unique elements. This article dives deep into Python sets, covering their creation, common operations like adding, removing,