Open In App

Priority Queue in Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A priority queue is like a regular queue, but each item has a priority. Instead of being served in the order they arrive, items with higher priority are served first. For example, In airlines, baggage labeled “Business” or “First Class” usually arrives before the rest.

Key properties of priority queue:

  • High-priority elements are dequeued before low-priority ones.
  • If two elements have the same priority, they are dequeued in their order of insertion like a queue.

Key differences between priority queue and queue

Understanding the difference between these two structures makes it easier to choose the right one for situations like scheduling tasks, managing resources, or solving problems in programs.

Feature

Regular Queue

Priority Queue

Order of Processing

First-In-First-Out (FIFO)

Based on priority

Element Dequeue Order

In order of arrival

Highest priority first

Handling Same Priority

Based on arrival time

Based on arrival time (if priority is same)

Sorting Effect

No sorting

Acts like a sorted structure when dequeued

Below is a simple implementation of the priority queue.

[GFGTABS]
Python

def insert(q, d):
    q.append(d)

def delete(q):
    try:
        m = 0
        for i in range(len(q)):
            if q[i] > q[m]:
                m = i
        item = q[m]
        del q[m]
        return item
    except IndexError:
        print("Queue empty.")
        exit()

def is_empty(q):
    return len(q) == 0

if __name__ == '__main__':
    q = []

    insert(q, 12)
    insert(q, 1)
    insert(q, 14)
    insert(q, 7)

    print(q)
    print("Removed elements:")
    while not is_empty(q):
        print(delete(q))


[/GFGTABS]

Output

[12, 1, 14, 7]
Removed elements:
14
12
7
1

Explanation:

  • insert(q, d) adds element d to the end of the queue q using append().
  • delete(q) finds and removes the highest priority (max value) element from q. If the queue is empty, it prints “Queue empty.” and exits.
  • is_empty(q) returns True if the queue q is empty, otherwise False.
  • In the __main__ block while loop is used to repeatedly remove and print the highest priority element using the delete() function until the queue becomes empty.

Applications of priority queue

Let’s understand the applications of a priority queue because they demonstrate how this data structure can be utilized in real-world scenarios to manage tasks efficiently. Here are some key applications:

  • Task Scheduling (Operating Systems) manages tasks by priority, executing high-priority tasks first in real-time systems.
  • Dijkstra’s Shortest Path Algorithm uses a priority queue to find the shortest path by selecting the nearest node.
  • Huffman Encoding (Data Compression) combines least frequent symbols using a priority queue to reduce data size.
  • Merging Multiple Sorted Lists merges sorted lists by selecting the smallest element from each list.
  • A Search Algorithm (Pathfinding) prioritizes nodes based on cost to find the shortest path in navigation or games.

Types of priority queue

Let’s understand the different types of priority queues because they define how elements are prioritized and dequeued based on their associated priority. There are two main types:

  • Max Priority Queue: The element with the highest priority is dequeued first. It’s commonly used when you need to process the most important or largest element first.
  • Min Priority Queue: The element with the lowest priority is dequeued first. It’s useful for problems like finding the smallest element or processing tasks with the least urgency first.


Next Article

Similar Reads