Python Program to Implement a Priority Queue
Intermediate · Data structures
A priority queue is a queue where each item has a priority, and the most urgent item is removed first, whatever order the items arrived in. Hospitals treat patients this way, and computers use it to schedule tasks. This program uses the `heapq` module, where the smallest number comes out first, so priority 1 is the most urgent.
Program
Added: Reply to emails (priority 3) Added: Fix the payment bug (priority 1) Added: Plan next week (priority 4) Added: Prepare the slides (priority 2) Next up: Fix the payment bug Doing: Fix the payment bug (priority 1) Doing: Prepare the slides (priority 2) Doing: Reply to emails (priority 3) Doing: Plan next week (priority 4) Nothing to do: the priority queue is empty
How it works
- Each item is stored as a tuple
(priority, name), and tuples compare by their first value, so the priority decides the order. heapq.heappush()adds an item andheapq.heappop()removes the one with the smallest priority, both quickly even for big queues.- The list is kept as a heap, an arrangement in which the smallest item is always at index 0, so
tasks[0]peeks at the next task without removing it. - The tasks were added with priorities 3, 1, 4, 2 but come out in the order 1, 2, 3, 4.
- Popping from an empty heap would crash, so
do_next_task()checks for the empty case first.
Other ways to write it
Using a sorted list
Queue in order: [(1, 'Bug fix'), (2, 'Slides'), (3, 'Emails')] Doing: Bug fix Doing: Slides Doing: Emails
Keeping the list sorted as items arrive also works and is easy to follow, but every insert has to search the list, so heapq is faster for long queues.
Biggest number first
Ben: 95 Asha: 82 Chitra: 77
heapq always removes the smallest item first, so storing the negative of each score turns that around and the highest score comes out first.
Try it yourself
Add two tasks with the same priority and see which one comes out first.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises