Priority Queue in Python (original) (raw)

Last Updated : 26 Apr, 2025

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:

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:

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:

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: