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.

--

--

Mike Sun
0 Followers

Enigmatically simple. Aspiring photographer and technopreneur based in Singapore. www.linkedin.com/in/mike-sun