Understand Python Priority Queue with Examples: A Beginner Guide – Python Tutorial

By | December 21, 2019

Python priority queque is another queue, which is not similar to fifo queue. It can save data with priority. We will use some examples to show python beginners how to use this queue in this tutorial.

What is priority queue?

Priority queue is a queue that contains data with a priority value, when you plan to read a data from this queue, you will get the data with the highest priority value.

How to use priority queue in python.

To use priority queue in python, there are some questions you must concern:

How to create a priority queue in python?

How to save and read data from this priority queue?

We will fix these problems one by one.

How to create a priority queue in python?

To create a priority queue, we can use python queue package. Here is an example:

import queue
max_size = 5
q=queue.PriorityQueue(max_size)

In this code, we create a priority queue which will contains max_size data. If max_size<=0, it will contains infinite data.

How to save data into a priority queue.

Differ from fifo queue in python, to save a data into a priority queue, you should set a priority value for each data. We can save a data like this:

q.put((priority_value, data))

Where priority_value is the priority of data, we will save this data with its priority. You should notice: the smaller of priority value, the higher priority of data. Here is an example:

q.put((3, 3))
q.put((-2,[1, 2]))
q.put((1, 'tutorialexample.com'))

In this example, we will save 3 data into a priority queue with their priorities.

How to get data from a priority queue?

We can use q.get() method to get a data from a priority queue. Here is an example:

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

The result is:

(-2, [1, 2])
(1, 'tutorialexample.com')
(3, 3)

From the result we can find this truth: the smaller of priority value, the higher priority of data.

However, if you save some data with the same priority value, you will get some errors. Here is an example:

q.put((1,[1, 2]))
q.put((1, 'tutorialexample.com'))

In this example, we will save 2 data into a priority with the same priority value 1. Run this code, you will get error:

python priority queue type error

Leave a Reply