Queues in Python

A queue is a linear data structure that follows the FIFO (First In, First Out) principle. The first element added is the first one removed. Queues are essential in scheduling, buffering, and graph traversal algorithms like BFS.

Concept of Queue (FIFO)

  • Enqueue: add element to the rear
  • Dequeue: remove element from the front
  • Front: view first element
  • isEmpty: check if queue is empty

Implementation of Queue

Using List (not efficient for dequeue)

queue = []
queue.append(10)
queue.append(20)

queue.pop(0)  # slow for large lists

Using collections.deque (recommended)

from collections import deque

queue = deque()
queue.append(10)      # enqueue
queue.append(20)

print(queue.popleft())  # dequeue -> 10

Common Queue Operations

Enqueue

queue.append(5)

Dequeue

queue.popleft()

Front

front = queue[0]

isEmpty

is_empty = len(queue) == 0

Types of Queues

Circular Queue

A queue where the last position connects back to the first to reuse space.

Priority Queue

Elements are removed based on priority, not insertion order.
Python uses heapq.

import heapq
pq = []
heapq.heappush(pq, 3)
heapq.heappush(pq, 1)
heapq.heappop(pq)  # 1

Applications of Queues

Scheduling

CPU task scheduling uses queues.

Buffering

Data streaming and IO buffering.

BFS (Breadth First Search)

Queues are core to BFS in graphs and trees.

Summary

Queues are essential for order-based processing. Learn deque well because it’s the standard queue tool in Python.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *