Implementing a Priority Queue in Python Using heapq
This article explains how to implement a priority queue in Python using the built‑in heapq module, demonstrates extracting smallest and largest elements from price lists, and provides a full PriorityQueue class with push, pop, and is_empty methods, illustrated with stock portfolio examples.
Priority queues are data structures where each element has an associated priority, and higher‑priority elements are served before lower‑priority ones; they are commonly implemented with a heap.
The article shows how to use Python's built‑in heapq module to work with priority queues, starting with importing the module:
import heapqIt demonstrates extracting the three smallest and three largest values from a list of IBM stock prices using heapq.nsmallest and heapq.nlargest :
print(heapq.nsmallest(3, ibm_prices)) print(heapq.nlargest(3, ibm_prices))Next, it applies these functions to a portfolio of stock dictionaries, selecting the cheapest and most expensive stocks with a key function:
cheap_stocks = heapq.nsmallest(3, portfolio, key=lambda s: s['price']) expensive_stocks = heapq.nlargest(3, portfolio, key=lambda s: s['price'])The article then builds a reusable PriorityQueue class, defining an initializer, an is_empty check, a push method that uses heapq.heappush , and a pop method that uses heapq.heappop :
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def is_empty(self):
return not self._queue
def push(self, item, priority):
heapq.heappush(self._queue, (priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]A simple Stock class is also defined to hold ticker, price, and share information, with a custom __repr__ for readable output:
class Stock:
def __init__(self, stock_ticker, stock_price, stock_share):
self.stock_ticker = stock_ticker
self.stock_price = stock_price
self.stock_share = stock_share
def __repr__(self):
return 'Stock({}, {}, {})'.format(self.stock_ticker, self.stock_price, self.stock_share)The example creates a PriorityQueue instance, pushes several Stock objects with different priorities, and then prints them in order of priority:
q = PriorityQueue()
q.push(Stock('IBM', 108.68, 200), 4)
q.push(Stock('HPQ', 17.18, 125), 1)
q.push(Stock('TWTR', 29.29, 95), 3)
q.push(Stock('UBER', 22.6, 50), 2)
q.push(Stock('AAPL', 277.97, 75), 6)
q.push(Stock('FB', 170.28, 40), 5)
while not q.is_empty():
print(q.pop())The article concludes that the heap‑based priority queue offers excellent performance when only a small number of extreme elements are needed, and encourages readers to explore alternative implementations.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.