brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's heapq.nlargest picks the top few without sorting everything

Python
~/tips/tip-python-heapq-nlargest

import heapq

Get the biggest or smallest n items from a large list or a generator.

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

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link