When I want the ten biggest files or the five slowest requests, sorting the full list and slicing works, but heapq.nlargest says what I mean and doesn’t need the whole list in memory.
import heapq
from pathlib import Path
files = (p for p in Path(".").rglob("*") if p.is_file())
for p in heapq.nlargest(5, files, key=lambda p: p.stat().st_size):
print(p.stat().st_size, p)
It walks through the input once and only keeps the current top n, so it works fine on a generator like the one above. A folder with a few hundred thousand files never turns into a giant list. heapq.nsmallest does the opposite, for example the oldest backups by modification time.
The result is sorted biggest first, and the key argument works like the one for sorted().
It’s not always faster, though. The docs point out that for n close to the size of the input, a plain sorted() wins, and for n equal to 1 max() and min() are the better choice. I’d use nlargest when n is small and the input is big or arrives as a stream. Also note the key in my example calls stat() again when printing; for big trees, store the size in a tuple first.
Further reading: heapq.nlargest