Two small modules of the standard library solve problems that you would otherwise program by hand: keeping a list sorted and always getting the smallest element.
bisect: binary search in sorted lists
bisect uses binary search, so it finds the position in O(log n) instead of scanning the list. The list must be sorted. bisect_left returns the position *before* equal items and bisect_right (or bisect) *after* them. insort inserts keeping the order.
import bisect
limits = [10, 20, 30, 40] # SORTED list
print(bisect.bisect_left(limits, 25)) # 2 (25 would go between 20 and 30)
print(bisect.bisect_left(limits, 30)) # 2 (before the 30 that is already there)
print(bisect.bisect_right(limits, 30)) # 3 (after the 30 that is already there)
bisect.insort(limits, 25) # inserts keeping the order
print(limits) # [10, 20, 25, 30, 40]
Turning a number into a category
The most convenient use replaces a chain of if/elif: the limits go in a list and the result is looked up by position.
import bisect
def letter(score):
limits = [60, 70, 80, 90]
letters = "FDCBA"
return letters[bisect.bisect_right(limits, score)]
print(letter(59), letter(60), letter(85), letter(90)) # F D B A
You practice it in Grade table with bisect.
heapq: heaps and priority queues
A heap is a structure that always keeps the smallest element at hand. heapq works on a normal list: heappush adds, heappop removes the smallest, both in O(log n). To order by priority you store tuples (priority, item).
import heapq
heap = []
for task in [(3, "third"), (1, "first"), (2, "second")]:
heapq.heappush(heap, task) # (priority, item)
while heap:
priority, item = heapq.heappop(heap) # the smallest always comes out
print(priority, item)
# 1 first
# 2 second
# 3 third
The k largest or smallest
If you only need the extremes, nlargest and nsmallest are more efficient than sorting the whole list, and they accept key=.
import heapq
numbers = [5, 1, 9, 3, 7, 2]
print(heapq.nlargest(3, numbers)) # [9, 7, 5]
print(heapq.nsmallest(2, numbers)) # [1, 2]
words = ["pear", "kiwi", "banana", "fig"]
print(heapq.nlargest(2, words, key=len)) # ['banana', 'pear']
You apply it in The k largest and smallest. Heaps are studied in more detail in the data structures lesson.
| I need… | Use |
|---|---|
| To know where a value goes in a sorted list | bisect |
| To insert keeping the order | bisect.insort |
| To always take out the smallest | heapq.heappop |
| The k largest or smallest | heapq.nlargest / nsmallest |