How do I keep the largest few items without sorting everything?

Find the largest trades with heapq.nlargest, see how a heap keeps its smallest item first, and keep a running top five as trades arrive.

After this lesson, you can find the largest few trades and keep a running top five as new trades arrive.

How do I find the largest trades in one call?

heapq.nlargest(5, sizes) returns the five largest sizes, largest first, without sorting the whole list. For seven made-up trades, it returns 900, 400, 400, 300 and 150 shares, the same as sorted(sizes, reverse=True)[:5], which sorts every trade first.

The trades arrive in order, each a size in shares and a ticker. key= makes nlargest compare one field and return the whole trade.

The following box finds the five largest sizes and the two largest trades.

import heapq

trades = [(400, "BBB"), (150, "AAA"), (900, "CCC"), (300, "BBB"), (50, "DDD"), (50, "AAA"), (400, "CCC")]
sizes = [size for size, ticker in trades]
print(heapq.nlargest(5, sizes))
print(heapq.nlargest(2, trades, key=lambda trade: trade[0]))
[900, 400, 400, 300, 150]
[(900, 'CCC'), (400, 'BBB')]

On a million trades, nlargest keeps only five candidates while it reads the list, which takes far less time than sorting all of them.

How do I keep the top five as trades arrive?

A heap is a list kept in an order where position 0 holds the smallest item, so best[0] is the smallest of the five sizes kept. Each new size enters while fewer than five are kept, and after that replaces the smallest only when it is larger. The last trade, CCC’s 400 shares, replaces the 50.

heapq.heappush(best, size) adds a size and keeps the heap order, and heapq.heapreplace(best, size) removes the smallest and adds the new size in one step. Sorting best for printing leaves the heap itself unchanged.

The following box keeps the top five as each trade arrives.

best = []
for size in sizes:
    if len(best) < 5:
        heapq.heappush(best, size)
    elif size > best[0]:
        heapq.heapreplace(best, size)
    print(size, sorted(best, reverse=True))
400 [400]
150 [400, 150]
900 [900, 400, 150]
300 [900, 400, 300, 150]
50 [900, 400, 300, 150, 50]
50 [900, 400, 300, 150, 50]
400 [900, 400, 400, 300, 150]

The second 50 ties the smallest kept size and changes nothing. A live feed can keep its top five this way without storing every trade.

Your turn

Print the two smallest trades with their tickers. You should see DDD’s 50 shares first and AAA’s 50 second, the order in which they arrived.

heapq.nsmallest works like nlargest, smallest first, and keeps the arrival order for ties.

print(heapq.nsmallest(2, trades, key=lambda trade: trade[0]))
[(50, 'DDD'), (50, 'AAA')]