Reading history

Python heapq and bisect Modules: Priority Queues and Sorted Lists

6 min read 2 views

Use heapq for priority queues, nlargest and nsmallest, and bisect for fast lookups, grade boundaries and keeping lists sorted with insort.

Two small built-in modules solve two very common problems. heapq always gives you the smallest item first, which is exactly what a hospital queue, a task scheduler or a “top 10” list needs. bisect finds positions in a sorted list very quickly, which is perfect for grade boundaries, timetables and keeping a list sorted as it grows. Both work on ordinary Python lists.

In this lesson you will learn

  • Building a priority queue with heappush and heappop
  • Finding the largest or smallest items with nlargest and nsmallest
  • heapify and merge
  • Looking up positions with bisect_left and bisect_right
  • Inserting in order with insort, and counting values in a range

You should know lists, tuples and lambda functions.

heapq: Smallest First

import heapq

# heapq turns a plain list into a min-heap: the smallest item is always at [0]
patients = []
heapq.heappush(patients, (3, "sprained ankle"))
heapq.heappush(patients, (1, "chest pain"))
heapq.heappush(patients, (2, "high fever"))
heapq.heappush(patients, (3, "small cut"))
print("next up:", patients[0])

while patients:
    priority, problem = heapq.heappop(patients)
    print(f"  treat (priority {priority}) {problem}")

scores = [72, 95, 58, 88, 99, 64, 81]
print("top 3:", heapq.nlargest(3, scores))
print("bottom 2:", heapq.nsmallest(2, scores))

h = scores[:]
heapq.heapify(h)                         # rearrange in place, O(n)
print("heap list:", h, "| smallest:", h[0])

# nlargest with a key
shops = [("Bashundhara", 4.6), ("Jamuna", 4.4), ("New Market", 4.1), ("Gulshan", 4.5)]
print("best rated:", heapq.nlargest(2, shops, key=lambda s: s[1]))

# Merge already-sorted lists lazily
print("merged:", list(heapq.merge([1, 4, 9], [2, 3, 10], [5])))

Output

next up: (1, 'chest pain')
  treat (priority 1) chest pain
  treat (priority 2) high fever
  treat (priority 3) small cut
  treat (priority 3) sprained ankle
top 3: [99, 95, 88]
bottom 2: [58, 64]
heap list: [58, 88, 64, 95, 99, 72, 81] | smallest: 58
best rated: [('Bashundhara', 4.6), ('Gulshan', 4.5)]
merged: [1, 2, 3, 4, 5, 9, 10]
  • A heap is a list arranged so that the smallest item is always at index 0. heappush adds an item and heappop removes and returns the smallest, both quickly, even for very large lists.
  • Storing (priority, problem) tuples makes a priority queue: tuples compare by their first item, so priority 1, the most urgent, comes out first.
  • When two priorities are equal, the tuples are compared by their second item. That is why “small cut” came before “sprained ankle”: alphabetical order, not arrival order. To serve equal priorities in arrival order, add a counter: (priority, count, problem).
  • nlargest and nsmallest return the top or bottom few items without sorting the whole list, and accept a key just like sorted.
  • heapify rearranges an existing list into a heap in place. The list is not fully sorted, only arranged so that h[0] is the smallest.
  • merge combines lists that are already sorted into one sorted stream.

bisect: Searching a Sorted List

import bisect

# bisect works on a list that is already sorted
marks = [33, 40, 50, 60, 70, 80]          # lower limits of each grade
grades = ["F", "D", "C", "B", "A-", "A", "A+"]

def grade(score):
    return grades[bisect.bisect_right(marks, score)]

for s in (25, 33, 59, 60, 79, 80, 95):
    print(f"  {s:>3} -> {grade(s)}")

# insort keeps a list sorted as you add to it
waiting = [10, 20, 40]
bisect.insort(waiting, 30)
bisect.insort(waiting, 5)
print("sorted insert:", waiting)

# Fast membership test in a sorted list: O(log n)
def contains(sorted_list, x):
    i = bisect.bisect_left(sorted_list, x)
    return i < len(sorted_list) and sorted_list[i] == x

print("has 30?", contains(waiting, 30), "| has 35?", contains(waiting, 35))

# Count values in a range [lo, hi]
ages = sorted([17, 22, 25, 25, 31, 40, 45, 52, 60])
lo, hi = 25, 45
n = bisect.bisect_right(ages, hi) - bisect.bisect_left(ages, lo)
print(f"ages {lo}-{hi}: {n} people")

# key= (Python 3.10+) searches by part of each item
bus_times = [("06:30", "Gabtoli"), ("07:15", "Mohakhali"), ("08:00", "Sayedabad")]
i = bisect.bisect_left(bus_times, "07:00", key=lambda b: b[0])
print("next bus after 07:00:", bus_times[i])

Output

   25 -> F
   33 -> D
   59 -> B
   60 -> A-
   79 -> A
   80 -> A+
   95 -> A+
sorted insert: [5, 10, 20, 30, 40]
has 30? True | has 35? False
ages 25-45: 5 people
next bus after 07:00: ('07:15', 'Mohakhali')
  • bisect_right(marks, score) returns how many grade boundaries are less than or equal to the score. That number is the position of the grade in the grades list, so one line replaces a long if/elif chain. The boundaries follow the SSC grading scale: 80 and above is A+, below 33 is F.
  • bisect_left and bisect_right differ only when the value is already in the list: left gives the position before equal items, right the position after them. A score of exactly 80 must count as A+, so bisect_right is the right choice here.
  • insort inserts a value in its correct place so the list stays sorted.
  • contains uses bisect_left to check membership in about 20 steps for a million items, instead of checking every item.
  • Subtracting two positions counts the values between two limits: 5 people are aged 25 to 45.
  • Since Python 3.10, key= lets you search a list of tuples by one part, here the departure time.

Speed Compared

TaskPlain listWith heapq or bisect
Take the smallest item repeatedlymin() scans every item each timeheappop: log n steps
Top 3 of a million scoressorted() sorts everythingnlargest(3, ...) keeps only 3
Is x in a sorted list?x in lst checks one by onebisect_left: log n steps

Common Mistakes

  1. Expecting a heap to be sorted. Only h[0] is guaranteed to be the smallest.
  2. Using bisect on an unsorted list. The answers will be meaningless.
  3. Looking for a max-heap in older Python. Before Python 3.14, heapq offered only min-heap functions, so push -value and negate it again when popping. Python 3.14 adds heappush_max and heappop_max.
  4. Pushing items that cannot be compared, such as dictionaries with equal priorities. Add a counter as a tie-breaker.

Practice Exercises

Exercise 1. Use a heap to always serve the customer with the largest order first.

Show answer
import heapq
orders = []
for amount, name in [(500, "Ria"), (2500, "Sabbir"), (1200, "Lima")]:
    heapq.heappush(orders, (-amount, name))
while orders:
    amount, name = heapq.heappop(orders)
    print(name, -amount)   # Sabbir 2500, Lima 1200, Ria 500

Exercise 2. Electricity is billed in slabs that start at 0, 76, 201, 301 and 401 units. Use bisect to find which slab (1 to 5) a reading of 250 units falls into.

Show answer
import bisect
starts = [0, 76, 201, 301, 401]
print(bisect.bisect_right(starts, 250))   # 3

Frequently Asked Questions

Should I use heapq or queue.PriorityQueue?

heapq is simpler and faster for a single thread. queue.PriorityQueue is built on the same idea but adds locking, so use it when several threads share the queue.

Why is a heap faster than sorting each time?

Adding or removing one item from a heap only rearranges a short path of about log n items. Sorting looks at every item again, which is much slower when you add and remove items often.

Summary

  • heapq keeps the smallest item at index 0; push and pop in log n time.
  • Use tuples for priorities; negate values for a max-heap (or use the _max functions in Python 3.14+).
  • bisect finds positions in sorted lists; insort keeps them sorted.
  • Both modules work on ordinary lists.

Next: Python @property and __slots__.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *