Python Priority Queue

Mike Sun
1 min readJun 18, 2020

simple implementation extending python’s list

Priority queue is very similar to queue except for the enqueue code. In my implementation, I will use tuples in list, with the first element of the tuple being the priority. 1 being the most urgent.

The queue will look like this, [(1, 1), (1, 2), (1, 3),(2,1),(3,1)]

Here is my code and explanation will be given below.

For enqueue, we first need to check if queue is empty. If true, we simply append the tuple. However, if queue is not empty, we would like to loop through the queue and check every single first element of tuple, which is our priority. Do take note that greater the priority number, the lower the priority. So be careful when I say priority is greater, I mean the absolute value and not the intuitive sense.

If the priority of new_element is greater or equal to priority of existing element, we will continue on checking. Once we reach a point where the priority of the new_element is less than that of the existing element, we will proceed to insert the new_element there.

If the above all fails, that can only mean the priority is not yet in the queue, hence simply append it at the back.

Happy coding.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Mike Sun
Mike Sun

Written by Mike Sun

Random tech blog for my fellow peers troubleshooting stuff. Things I wished I knew without needing to spend hours/days digging...

No responses yet

Write a response